﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Text;
using SCSService;
using SCS.Core.Models;
using SCS.Core.ViewModels;
using System.Collections;


namespace SCS.Core.Controllers
{
    public class StockController : BaseController
    {
        public ActionResult Index()
        {
            return RedirectToAction("ListTypeProduct");
        }

        #region "TypeProduct"
        public ActionResult AddTypeProduct()
        {
            var typeProduct = new Models.Collection.TypeProductCollection();
            int siteGuid = GetSiteGuid();
            
            int languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());

            ViewData["IsAdd"] = true;
            //ViewData["ListLanguage"] = new SelectList(Models.StockModel.GetListLanguage(), "LanguagesID", "countryName", languageId);

            ViewData["ListLanguage"] = new SelectList(Models.ModelsFontend.LanguageModel.GetListLanguageBySiteGuid(GetSiteGuid()), "LanguagesID", "countryName", languageId);

            ViewData["ListParent"] = new SelectList(GetListTypeProductDropBasic(null, null, null, null,null, StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter()), siteGuid), "TypeProductID", "TypeProductName");

            //ViewData["ListItem"] = Models.StockModel.GetListTypeProductItemByTypeID(null, GetSiteGuid());
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("DetailTypeProduct", typeProduct);
        }

        [HttpPost]
        public JsonResult SaveAddTypeProductItem(List<string> ids)
        {
            //string TypeProductName, string TypeProductDes, string TypeProductAbstract, string Title, string MetaKeyword, 
            //string MetaDescription, int LanguagesID
            int itemID = 0;

            if (ids[6] != string.Empty && ids[6] != null)
            {
                SCSService.Type_Product_Item item = new Type_Product_Item();
                item.TypeProductName = ids[0].ToString();
                item.TypeProductDes = ids[1].ToString();
                item.TypeProductAbstract = ids[2].ToString();
                item.LanguagesID = int.Parse(ids[6].ToString());
                item.TypeProductID = null;
                item.Title = ids[3].ToString();
                item.MetaKeyword = ids[4].ToString();
                item.MetaDescription = ids[5].ToString();

                itemID = Models.StockModel.CreateTypeProductItem(item);     
            }
            return Json(itemID);
        }

        

        [HttpPost]
        public JsonResult UpdateTypeProductItem(List<string> ids)
        {
            //string TypeProductName, string TypeProductDes, string TypeProductAbstract, string Title, string MetaKeyword, 
            //string MetaDescription,int TypeProductID, int LanguagesID,int TypeProductItemID
            //int itemID = 0;

            if (ids[8] != string.Empty && ids[8] != null)
            {
                SCSService.Type_Product_Item item = Models.StockModel.GetTypeProductItemByID(int.Parse(ids[8]));
                item.TypeProductName = ids[0].ToString();
                item.TypeProductDes = ids[1].ToString();
                item.TypeProductAbstract = ids[2].ToString();
                item.Title = ids[3].ToString();
                item.MetaKeyword = ids[4].ToString();
                item.MetaDescription = ids[5].ToString();
                item.TypeProductID = int.Parse(ids[6].ToString());
                item.LanguagesID = int.Parse(ids[7].ToString());
                item.TypeProductItemID = int.Parse(ids[8].ToString());

                Models.StockModel.UpdateTypeProductforItem(item);
            }
            return Json(1);
        }


        [HttpPost]
        public JsonResult GetTypePByLandTypeProductId(List<string> ids)
        {
            
            string languagesId=ids[0].ToString();
            string typeId = ids[1].ToString();
            SCSService.Type_Product_Item items = new Type_Product_Item();
            if (typeId != null && languagesId!=null)
            {
                if (typeId != string.Empty && languagesId!=string.Empty)
                {
                    items = Models.StockModel.GetTypeProductItemByLangIDandTypeID(int.Parse(languagesId),int.Parse(typeId));
                }

            }
            string result = "";

            if (items != null)
            {
                result += items.TypeProductItemID + "|";
                if (items.TypeProductName != null)
                {
                    result += items.TypeProductName + "|";
                }
                else
                {
                    result += "" + "|";
                }

                if (items.TypeProductDes != null)
                {
                    result += items.TypeProductDes + "|";
                }
                else
                {
                    result += "" + "|";
                }

                if (items.TypeProductAbstract != null)
                {
                    result += items.TypeProductAbstract + "|";
                }
                else
                {
                    result += "" + "|";
                }

                if (items.Title != null)
                {
                    result += items.Title + "|";
                }
                else
                {
                    result += "" + "|";
                }

                if (items.MetaKeyword != null)
                {
                    result += items.MetaKeyword + "|";
                }
                else
                {
                    result += "" + "|";
                }

                if (items.MetaDescription != null)
                {
                    result += items.MetaDescription + "|";
                }
                else
                {
                    result += "" + "|";
                }

            }

            return this.Json(result);

        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveAdd(FormCollection collection)
        {
            var typeProduct = new Models.Collection.TypeProductCollection();
            TryUpdateModel(typeProduct);
            int typeId = 0;
            try
            {

                //Create Type Product
                SCSService.Type_Product type = new Type_Product();
                type.TypeProductName = typeProduct.TypeProductName;
                type.TypeProductDes = typeProduct.TypeProductDes;
                type.TypeProductAbstract = typeProduct.TypeProductAbstract;
                type.TypeProductImage = typeProduct.TypeProductImage;
                type.TypeProductStatus = 1; //is active
                type.LanguagesID = typeProduct.LanguagesID;
                //type.TypeProductImage = "/Content/images/placeholder.jpg";
                if (typeProduct.ParentTypeProductID != 0)
                {
                    type.ParentTypeProductID = (int)typeProduct.ParentTypeProductID;
                }
                type.Title = typeProduct.Title != string.Empty ? typeProduct.Title : typeProduct.TypeProductName;
                type.MetaKeyword = typeProduct.MetaKeyword;
                type.MetaDescription = typeProduct.MetaDescription;
                type.SiteGuid = DefaultSiteGuidGetter();
                type.TypeProductParam = typeProduct.TypeProductParam;

                //type.ParentTypeProductID = typeProduct.ParentTypeProductID;

                typeId = Models.StockModel.CreateTypeProduct(type);

                //Update List TypeProductItem
                if (typeId > 0)
                {
                    if (typeProduct.ArrTypeItemsID != null && typeProduct.ArrTypeItemsID != "")
                    {
                        string[] arrItems = typeProduct.ArrTypeItemsID.Split(',');

                        for (int i = 0; i < arrItems.Length; i++)
                        {
                            if (!string.IsNullOrEmpty(arrItems[i]))
                            {
                                SCSService.Type_Product_Item items = Models.StockModel.GetTypeProductItemByID(int.Parse(arrItems[i].ToString()));
                                items.TypeProductID = typeId;

                                Models.StockModel.UpdateTypeProductforItem(items);
                            }
                        }
                    }
                   
                }
                //Create 1 source Items for language
                SCSService.Type_Product_Item item = new Type_Product_Item();
                item.TypeProductName = typeProduct.TypeProductName;
                item.TypeProductDes = typeProduct.TypeProductDes;
                item.TypeProductAbstract = typeProduct.TypeProductAbstract;
                item.LanguagesID = typeProduct.LanguagesID;
                item.TypeProductID = typeId;
                item.Title = type.Title;
                item.MetaKeyword = typeProduct.MetaKeyword;
                item.MetaDescription = typeProduct.MetaDescription;

                Models.StockModel.CreateTypeProductItem(item);    
                
                
                ViewData["Result"] = "Create Type Product Success!";

            }
            catch
            {
                return View("DetailTypeProduct", new Models.Collection.TypeProductCollection());
            }
            return Redirect("/" + DefaultSiteGuidGetter() + "/" + StockModel.GetLanguageByID(int.Parse(collection.Get("LanguagesID"))).countryCode + "/Stock/ListTypeProduct");
        }
      
        public ActionResult EditTypeProduct(int id)
        {
            ViewData["IsAdd"] = false;
            int siteGuid = GetSiteGuid();
            
            Type_Product type = Models.StockModel.GetTypeProduct(id);
            var typeProduct = new Models.Collection.TypeProductCollection();
            typeProduct.TypeProductID = type.TypeProductID;
            typeProduct.TypeProductName = type.TypeProductName;
            typeProduct.TypeProductAbstract = type.TypeProductAbstract;
            typeProduct.TypeProductDes = type.TypeProductDes;
            typeProduct.TypeProductImage = type.TypeProductImage;

            if (type.TypeProductStatus != null)
            {
                typeProduct.TypeProductStatus = (int)type.TypeProductStatus;
            }

            if (type.LanguagesID != null)
            {
                typeProduct.LanguagesID = (int)type.LanguagesID;
            }

            if (type.ParentTypeProductID != null)
            {
                typeProduct.ParentTypeProductID = (int)type.ParentTypeProductID;
            }

            typeProduct.Title = type.Title;
            typeProduct.MetaKeyword = type.MetaKeyword;
            typeProduct.MetaDescription = type.MetaDescription;
            typeProduct.TypeProductParam = type.TypeProductParam;
            var listTypeID = Models.StockModel.GetListTypeProductItemByTypeID(id, siteGuid);
            string arrId = "";
            foreach (var item in listTypeID)
            {
                arrId += item + ",";
            }
            typeProduct.ArrTypeItemsID = arrId.Length > 1 ? arrId.Substring(0, arrId.LastIndexOf(',')) : "";
            ViewData["ListLanguage"] = new SelectList(Models.ModelsFontend.LanguageModel.GetListLanguageBySiteGuid(GetSiteGuid()), "LanguagesID", "countryName", type.LanguagesID != null ? type.LanguagesID : 0);
            
            //Bug 17/12/2011 Loai bo chinh no khoi list
            ViewData["ListParent"] = new SelectList(GetListTypeProductDropBasicForEdit(null, null, null, null,null, StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter()), siteGuid,id), "TypeProductID", "TypeProductName", type.ParentTypeProductID != null ? type.ParentTypeProductID : 0);
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("DetailTypeProduct", typeProduct);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveEdit(FormCollection collection)
        {
            var typeProduct = new Models.Collection.TypeProductCollection();
            TryUpdateModel(typeProduct);
            int siteGuid = GetSiteGuid();
            
            try
            {

                //Update Type Product
                SCSService.Type_Product type = Models.StockModel.GetTypeProduct(typeProduct.TypeProductID);
                type.TypeProductName = typeProduct.TypeProductName;
                type.TypeProductDes = typeProduct.TypeProductDes;
                type.TypeProductAbstract = typeProduct.TypeProductAbstract;
                if (typeProduct.TypeProductImage != null)
                {
                    type.TypeProductImage = typeProduct.TypeProductImage;
                }

                if (bool.Parse(Request.Form.GetValues("TypeProductStatus")[0]))
                {
                    type.TypeProductStatus = 1;
                }
                else
                    type.TypeProductStatus = 0;


                if (collection.Get("LanguagesID") != "")
                {
                    type.LanguagesID = int.Parse(collection.Get("LanguagesID"));
                }

                if (collection.Get("ParentTypeProductID") != "")
                {
                    type.ParentTypeProductID = int.Parse(collection.Get("ParentTypeProductID"));
                }

                type.TypeProductID = typeProduct.TypeProductID;
                type.Title = typeProduct.Title != string.Empty ? typeProduct.Title : typeProduct.TypeProductName;
                type.MetaKeyword = typeProduct.MetaKeyword;
                type.MetaDescription = typeProduct.MetaDescription;
                type.TypeProductParam = typeProduct.TypeProductParam;

                //Call Update method
                Models.StockModel.UpdateTypeProduct(type);

                ViewData["Result"] = "Update Type Product Success!";

            }
            catch
            {
                return View("DetailTypeProduct", new Models.Collection.TypeProductCollection());
            }
            return Redirect("/" + DefaultSiteGuidGetter() + "/" + StockModel.GetLanguageByID(int.Parse(collection.Get("LanguagesID"))).countryCode + "/Stock/EditTypeProduct/" + typeProduct.TypeProductID);
        }
        #region TypeProduct gồm nhiều ngôn ngữ
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveAddTypeProductLanguage(FormCollection collection)
        {
            var typeProduct = new Models.Collection.TypeProductCollection();
            TryUpdateModel(typeProduct);
            int languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());

            int typeId = 0;
            try
            {

                //Create Type Product
                SCSService.Type_Product type = new Type_Product();
                type.TypeProductName = typeProduct.TypeProductName;
                type.TypeProductDes = typeProduct.TypeProductDes;
                type.TypeProductAbstract = typeProduct.TypeProductAbstract;
                type.TypeProductImage = typeProduct.TypeProductImage;
                type.TypeProductStatus = 1; //is active
                type.LanguagesID = 1;//Ngôn ngữ gốc luôn là tiếng việt có id =1.
                //type.TypeProductImage = "/Content/images/placeholder.jpg";
                if (typeProduct.ParentTypeProductID != 0)
                {
                    type.ParentTypeProductID = (int)typeProduct.ParentTypeProductID;
                }
                type.Title = typeProduct.Title != string.Empty ? typeProduct.Title : typeProduct.TypeProductName;
                type.MetaKeyword = typeProduct.MetaKeyword;
                type.MetaDescription = typeProduct.MetaDescription;
                type.SiteGuid = DefaultSiteGuidGetter();
                type.TypeProductParam = typeProduct.TypeProductParam;

                //type.ParentTypeProductID = typeProduct.ParentTypeProductID;

                typeId = Models.StockModel.CreateTypeProduct(type);

                //Update List TypeProductItem
                if (typeId > 0)
                {

                    ViewData["ListLanguage"] = new SelectList(Models.ModelsFontend.LanguageModel.GetListLanguageBySiteGuid(GetSiteGuid()), "LanguagesID", "countryName", languageId != null ? languageId : 0);

                    foreach (SelectListItem slitem in (SelectList)ViewData["ListLanguage"])
                    {
                        if (slitem.Value != "1")
                        {
                            //string TypeproductItemID = Request.Form["TypeProductItemId" + slitem.Value];
                            //if (!string.IsNullOrEmpty(Request.Form["TypeProductName_Items" + slitem.Value]))
                            //{
                                SCSService.Type_Product_Item Type_Product_ItemSvc = new Type_Product_Item();
                                Type_Product_ItemSvc.TypeProductName = Request.Form["TypeProductName_Items" + slitem.Value];
                                Type_Product_ItemSvc.TypeProductDes = Request.Form["TypeProductDes_Items" + slitem.Value];
                                //Type_Product_ItemSvc.TypeProductAbstract = Request.Form["TypeProductAbstract"+slitem.Value];
                                Type_Product_ItemSvc.LanguagesID = int.Parse(slitem.Value);
                                Type_Product_ItemSvc.TypeProductID = typeId;
                                Type_Product_ItemSvc.Title = Request.Form["Title_Items" + slitem.Value];
                                Type_Product_ItemSvc.MetaKeyword = Request.Form["MetaKeyword_Items" + slitem.Value];
                                Type_Product_ItemSvc.MetaDescription = Request.Form["MetaDescription_Items" + slitem.Value];

                                Models.StockModel.CreateTypeProductItem(Type_Product_ItemSvc);
                            //}
                        }
                    }
                }


                //Create 1 source Items for language
                SCSService.Type_Product_Item item = new Type_Product_Item();
                item.TypeProductName = typeProduct.TypeProductName;
                item.TypeProductDes = typeProduct.TypeProductDes;
                item.TypeProductAbstract = typeProduct.TypeProductAbstract;
                item.LanguagesID = 1;//Ngôn ngữ gốc là tiếng việt.
                item.TypeProductID = typeId;
                item.Title = type.Title;
                item.MetaKeyword = typeProduct.MetaKeyword;
                item.MetaDescription = typeProduct.MetaDescription;

                Models.StockModel.CreateTypeProductItem(item);

                ViewData["IsAdd"] = false;
                ViewData["Result"] = "Create Type Product Success!";

            }
            catch
            {
                return View("DetailTypeProduct", new Models.Collection.TypeProductCollection());
            }
            return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/Stock/ListTypeProduct");
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveEditTypeProducLanguage(FormCollection collection)
        {

            var typeProduct = new Models.Collection.TypeProductCollection();
            TryUpdateModel(typeProduct);
            int siteGuid = GetSiteGuid();
            int languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());

            try
            {


                //Update Type Product
                SCSService.Type_Product type = Models.StockModel.GetTypeProduct(typeProduct.TypeProductID);
                type.TypeProductName = typeProduct.TypeProductName;
                type.TypeProductDes = typeProduct.TypeProductDes;
                type.TypeProductAbstract = typeProduct.TypeProductAbstract;
                if (typeProduct.TypeProductImage != null)
                {
                    type.TypeProductImage = typeProduct.TypeProductImage;
                }

                if (bool.Parse(Request.Form.GetValues("TypeProductStatus")[0]))
                {
                    type.TypeProductStatus = 1;
                }
                else
                    type.TypeProductStatus = 0;


                if (collection.Get("LanguagesID") != "")
                {
                    type.LanguagesID = 1;
                }

                if (!string.IsNullOrEmpty(collection.Get("ParentTypeProductID")))
                {
                    type.ParentTypeProductID = int.Parse(collection.Get("ParentTypeProductID"));
                }

                type.TypeProductID = typeProduct.TypeProductID;
                type.Title = typeProduct.Title != string.Empty ? typeProduct.Title : typeProduct.TypeProductName;
                type.MetaKeyword = typeProduct.MetaKeyword;
                type.MetaDescription = typeProduct.MetaDescription;
                type.TypeProductParam = typeProduct.TypeProductParam;

                //Call Update method
                Models.StockModel.UpdateTypeProduct(type);

                //Update List TypeProductItem
                if (type.TypeProductID > 0)
                {

                    ViewData["ListLanguage"] = new SelectList(Models.ModelsFontend.LanguageModel.GetListLanguageBySiteGuid(GetSiteGuid()), "LanguagesID", "countryName", languageId != null ? languageId : 0);

                    foreach (SelectListItem slitem in (SelectList)ViewData["ListLanguage"])
                    {
                        if (slitem.Value != "1")
                        {
                            //update ngôn ngữ khi ngôn ngữ dã được tạo
                            if (!string.IsNullOrEmpty(Request.Form["TypeProductItemID" + slitem.Value]))
                            {
                                SCSService.Type_Product_Item Type_Product_ItemSvc = new Type_Product_Item();

                                Type_Product_ItemSvc.TypeProductItemID = int.Parse(Request.Form["TypeProductItemID" + slitem.Value]);
                                Type_Product_ItemSvc.TypeProductName = Request.Form["TypeProductName_Items" + slitem.Value];
                                Type_Product_ItemSvc.TypeProductDes = Request.Form["TypeProductDes_Items" + slitem.Value];
                                //Type_Product_ItemSvc.TypeProductAbstract = Request.Form["TypeProductAbstract"+slitem.Value];
                                Type_Product_ItemSvc.LanguagesID = int.Parse(slitem.Value);
                                Type_Product_ItemSvc.TypeProductID = type.TypeProductID;
                                Type_Product_ItemSvc.Title = Request.Form["Title_Items" + slitem.Value];
                                Type_Product_ItemSvc.MetaKeyword = Request.Form["MetaKeyword_Items" + slitem.Value];
                                Type_Product_ItemSvc.MetaDescription = Request.Form["MetaDescription_Items" + slitem.Value];

                                Models.StockModel.UpdateTypeProductByTypeProductItemId(Type_Product_ItemSvc);
                            }
                            else
                            {
                                //Ngôn ngữ sẽ được tạo mới
                                if (!string.IsNullOrEmpty(Request.Form["TypeProductName_Items" + slitem.Value]))
                                {
                                    SCSService.Type_Product_Item Type_Product_ItemSvc = new Type_Product_Item();
                                    Type_Product_ItemSvc.TypeProductName = Request.Form["TypeProductName_Items" + slitem.Value];
                                    Type_Product_ItemSvc.TypeProductDes = Request.Form["TypeProductDes_Items" + slitem.Value];
                                    //Type_Product_ItemSvc.TypeProductAbstract = Request.Form["TypeProductAbstract"+slitem.Value];
                                    Type_Product_ItemSvc.LanguagesID = int.Parse(slitem.Value);
                                    Type_Product_ItemSvc.TypeProductID = type.TypeProductID;
                                    Type_Product_ItemSvc.Title = Request.Form["Title_Items" + slitem.Value];
                                    Type_Product_ItemSvc.MetaKeyword = Request.Form["MetaKeyword_Items" + slitem.Value];
                                    Type_Product_ItemSvc.MetaDescription = Request.Form["MetaDescription_Items" + slitem.Value];

                                    Models.StockModel.CreateTypeProductItem(Type_Product_ItemSvc);
                                }
                            }

                        }
                    }
                }





                ViewData["IsAdd"] = false;

                ViewData["Result"] = "Update Type Product Success!";

            }
            catch
            {
                return View("DetailTypeProduct", new Models.Collection.TypeProductCollection());
            }
            //return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/Stock/EditTypeProduct/" + typeProduct.TypeProductID);
            return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/Stock/ListTypeProduct");
        }
        #endregion
        public StringBuilder GetListTypeProductBuilder(int? id, int LanguageID, int siteGuid)
        {
            StringBuilder sb = new StringBuilder();
            return ListTypeProductBuilder(ref sb, id, true, LanguageID, siteGuid);
        }

        public StringBuilder ListTypeProductBuilder(ref StringBuilder sb, int? id, bool root, int LanguagesID, int siteGuid)
        {
            List<SCSService.Type_Product> listType = Models.StockModel.GetListTypeProductByParentId(id, LanguagesID, siteGuid);
            if (root)
            {
                sb.Append("<ul id='navigation'>" + "List Type Product");
            }
            else
            {
                sb.Append("<ul>");
            }

            foreach (var item in listType)
            {
                sb.Append("<li><a href='/" + siteGuid + "/" + StockModel.GetLanguageByID(LanguagesID).countryCode + "/Stock/EditTypeProduct/" + item.TypeProductID + "'>" + item.TypeProductName + "</a>");
                List<SCSService.Type_Product> listChild = Models.StockModel.GetListTypeProductByParentId(item.TypeProductID, LanguagesID, siteGuid);
                if (listChild.Count() > 0)
                {
                    ListTypeProductBuilder(ref sb, item.TypeProductID, false, LanguagesID, siteGuid);
                }
                sb.Append("</li>");
            }
            sb.Append("</ul>");

            return sb;
        }

        public StringBuilder GetListTypeProductBuilderCheckBox(int? id, int LanguageID, int siteGuid)
        {
            StringBuilder sb = new StringBuilder();
            return ListTypeProductBuilderCheckBox(ref sb, id, true, LanguageID, siteGuid);
        }

        public StringBuilder ListTypeProductBuilderCheckBox(ref StringBuilder sb, int? id, bool root, int LanguagesID, int siteGuid)
        {
            List<SCSService.Type_Product> listType = Models.StockModel.GetListTypeProductByParentId(id, LanguagesID, siteGuid);
            if (root)
            {
                sb.Append("<ul id='navigation'>" + "List Type Product");
            }
            else
            {
                sb.Append("<ul>");
            }

            foreach (var item in listType)
            {
                sb.Append("<li><input type='checkbox' id='" + item.TypeProductID + "' /><a href='/" + siteGuid + "/" + StockModel.GetLanguageByID(LanguagesID).countryCode + "/Stock/EditTypeProduct/" + item.TypeProductID + "'>" + item.TypeProductName + "</a>");
                List<SCSService.Type_Product> listChild = Models.StockModel.GetListTypeProductByParentId(item.TypeProductID, LanguagesID, siteGuid);
                if (listChild.Count() > 0)
                {
                    ListTypeProductBuilderCheckBox(ref sb, item.TypeProductID, false, LanguagesID, siteGuid);
                }
                sb.Append("</li>");
            }
            sb.Append("</ul>");

            return sb;
        }

        public List<Type_Product> GetListTypeProductDrop(int? id, int LanguagesID, int siteGuid)
        {
            List<Type_Product> sb = new List<Type_Product>();
            return ListTypeProductDrop(ref sb, id, true, LanguagesID, siteGuid);
        }

        public List<Type_Product> ListTypeProductDrop(ref List<Type_Product> sb, int? id, bool root, int LanguagesID, int siteGuid)
        {
            List<SCSService.Type_Product> listType = Models.StockModel.GetListTypeProductByParentId(id, LanguagesID, siteGuid);

            foreach (var item in listType)
            {
                if (!root)
                {
                    item.TypeProductName = "-" + item.TypeProductName;

                    Type_Product pa = Models.StockModel.GetTypeProduct((int)id);
                    foreach (var itemStr in sb)
                    {
                        if (itemStr.TypeProductID == pa.TypeProductID)
                        {
                            if (itemStr.TypeProductName.StartsWith("-"))
                            {
                                int laststr = itemStr.TypeProductName.LastIndexOf('-') + 1;
                                string addStr = itemStr.TypeProductName.Substring(0, laststr);
                                item.TypeProductName = addStr + item.TypeProductName;
                            }
                        }
                    }

                }


                sb.Add(item);
                List<SCSService.Type_Product> listChild = Models.StockModel.GetListTypeProductByParentId(item.TypeProductID, LanguagesID, siteGuid);
                if (listChild.Count() > 0)
                {
                    ListTypeProductDrop(ref sb, item.TypeProductID, false, LanguagesID, siteGuid);
                }

            }

            return sb;
        }

        public List<Type_Product> GetListTypeProductDropBasic(string name, int? status, int? order,string param, int? id, int LanguagesID, int siteGuid)
        {
            List<Type_Product> sb = new List<Type_Product>();
            return ListTypeProductDropBasic(name, status, order,param, ref sb, id, true, LanguagesID, siteGuid);
        }

        public List<Type_Product> ListTypeProductDropBasic(string name, int? status, int? order,string param, ref List<Type_Product> sb, int? id, bool root, int LanguagesID, int siteGuid)
        {
            List<SCSService.Type_Product> listType = Models.StockModel.GetListTypeProductByParentIDSearch(name, status, order,param, id, LanguagesID, siteGuid);

            foreach (var item in listType)
            {
                if (!root)
                {
                    item.TypeProductName = Models.StockModel.GetTypeProduct((int)item.ParentTypeProductID).TypeProductName + ">>" + item.TypeProductName;

                    Type_Product pa = Models.StockModel.GetTypeProduct((int)id);
                    foreach (var itemStr in sb)
                    {
                        if (itemStr.TypeProductID == pa.TypeProductID)
                        {
                            if (itemStr.TypeProductName.Contains(">>"))
                            {
                                int laststr = itemStr.TypeProductName.LastIndexOf(">>") + 2;
                                string addStr = itemStr.TypeProductName.Substring(0, laststr);
                                item.TypeProductName = addStr + item.TypeProductName;
                            }
                        }
                    }

                }


                sb.Add(item);
                List<SCSService.Type_Product> listChild = Models.StockModel.GetListTypeProductByParentIDSearch(name, status, order,param, item.TypeProductID, LanguagesID, siteGuid);
                if (listChild.Count() > 0)
                {
                    ListTypeProductDropBasic(name, status, order,param, ref sb, item.TypeProductID, false, LanguagesID, siteGuid);
                }

            }

            return sb;
        }

        public List<Type_Product> GetListTypeProductDropBasicForEdit(string name, int? status, int? order, int? id,string param, int LanguagesID, int siteGuid,int idOwner)
        {
            List<Type_Product> sb = new List<Type_Product>();
            return ListTypeProductDropBasicForEdit(name, status, order, ref sb, id, true,param, LanguagesID, siteGuid, idOwner);
        }

        public List<Type_Product> ListTypeProductDropBasicForEdit(string name, int? status, int? order, ref List<Type_Product> sb, int? id, bool root,string param, int LanguagesID, int siteGuid,int idOwner)
        {
            List<SCSService.Type_Product> listType = Models.StockModel.GetListTypeProductByParentIDforEdit(name, status, order, id,param, LanguagesID, siteGuid,idOwner);

            foreach (var item in listType)
            {
                if (!root)
                {
                    item.TypeProductName = Models.StockModel.GetTypeProduct((int)item.ParentTypeProductID).TypeProductName + ">>" + item.TypeProductName;

                    Type_Product pa = Models.StockModel.GetTypeProduct((int)id);
                    foreach (var itemStr in sb)
                    {
                        if (itemStr.TypeProductID == pa.TypeProductID)
                        {
                            if (itemStr.TypeProductName.Contains(">>"))
                            {
                                int laststr = itemStr.TypeProductName.LastIndexOf(">>") + 2;
                                string addStr = itemStr.TypeProductName.Substring(0, laststr);
                                item.TypeProductName = addStr + item.TypeProductName;
                            }
                        }
                    }

                }


                sb.Add(item);
                List<SCSService.Type_Product> listChild = Models.StockModel.GetListTypeProductByParentIDforEdit(name, status, order, item.TypeProductID,param, LanguagesID, siteGuid,idOwner);
                if (listChild.Count() > 0)
                {
                    ListTypeProductDropBasicForEdit(name, status, order, ref sb, item.TypeProductID, false,param, LanguagesID, siteGuid,idOwner);
                }

            }

            return sb;
        }

        public ActionResult ChangeStatusTypeProduct(int? id, int? proid)
        {

            Models.StockModel.UpdateStatusTypeProduct(id, proid);

            //return Redirect(returnUrl);
            string outStr = "" + proid;
            return Json(outStr);
        }

        public ActionResult UdpateSortIndex(int? id, int? proid)
        {
            SCSService.ProductService proSvc = new ProductService();
            proSvc.UpdateSortOrder(id, proid);
            string result = "" + proid;
            return Json(result);
        }

        public static string GetGridThClass(ViewDataDictionary<SCS.Core.ViewModels.TypeProductViewModels> viewData, string sortField)
        {

            if ((string)viewData["SortField"] != sortField)
                return "";

            if ((string)viewData["SortDirection"] == "Asc")
                return "asc";

            return "desc";
        }

        public static string GetGridThOnClick(ViewDataDictionary<SCS.Core.ViewModels.TypeProductViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] == sortField && (string)viewData["SortDirection"] == "Asc")
                return "sort('" + sortField + "', 'Desc');";

            return "sort('" + sortField + "', 'Asc');";
        }

        public static SelectList SetOrder(int langauesID, int siteGuid)
        {

            int count = Models.StockModel.GetCountTypeProduct(langauesID, siteGuid);
            var tp = new List<string> { };
            for (int i = 1; i < (count + 1); i++)
            {
                tp.Add("" + i);
            }
            return new SelectList(tp);
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ListTypeProduct(string Name, int? StatusSearch, int? OrderSearch,string ParamSearch)
        {
            int currentPage = 1;
            int pageSize = 2000;
            string sortField = "SortOrder";
            string sortDirection = "Asc";

            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            
            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;

            ViewData["ListTypeProduct"] = GetListTypeProductBuilder(null, LanguageID, siteGuid);
            ViewData["SetOrder"] = SetOrder(LanguageID, siteGuid);

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return ListTypeProduct(Name, StatusSearch, OrderSearch, ParamSearch, currentPage, pageSize, sortField, sortDirection, null, siteGuid);


        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult ListTypeProduct(string Name, int? StatusSearch, int? OrderSearch, string ParamSearch, int? currentPage, int? pageSize, string sortField, string sortDirection, string gridAction, int? siteGuid)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            if (gridAction == "PageSizeChanged" || gridAction == "Sorted")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }


            if (pageSize == null)
            {
                pageSize = 2000;
            }

            if (siteGuid == null)
            {
                siteGuid = GetSiteGuid();
            }

            ViewData["currentPage"] = currentPage;
            ViewData["ListTypeProduct"] = GetListTypeProductBuilder(null, LanguageID, (int)siteGuid);
            ViewData["SetOrder"] = SetOrder(LanguageID, (int)siteGuid);

            var query = GetListTypeProductDropBasic(Name, StatusSearch, OrderSearch,ParamSearch, null, LanguageID, (int)siteGuid).AsQueryable();
            int totalRows = query.Count();

            if (!String.IsNullOrEmpty(sortField))
            {
                var param = Expression.Parameter(typeof(Type_Product), "Type_Product");
                var sortExpression = Expression.Lambda<Func<Type_Product, object>>
                                        (Expression.Convert(Expression.Property(param, sortField), typeof(object)), param);

                if (sortDirection == "Asc")
                    query = query.OrderBy(sortExpression);
                else
                    query = query.OrderByDescending(sortExpression);
            }

            int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            if (totalPages != 1)
            {
                //paging
                query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
            }


            UpdateSorterViewData(sortField, sortDirection);
            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize);

            var result = query.ToList();

            if (totalRows == 0)
                result = new List<SCSService.Type_Product>();

            // Set up our ViewModel
            var viewModel = new TypeProductViewModels
            {
                TypeProductList = result,
                //SearchForm =new Models.Collection.SearchTypeProductCollection()
                Name = Name,
                StatusSearch = StatusSearch,
                OrderSearch = OrderSearch
            };

            // Return the view
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View(viewModel);
        }

        public static bool CheckDeleteTypeProduct(int id)
        {
            int count = Models.StockModel.GetCountProductInTypeProduct(id);
            return count > 0 ? false : true;
        }

        public ActionResult DeleteTypeProduct(int id, string returnUrl)
        {
            if (CheckDeleteTypeProduct(id))
            {
                //xóa tất cả các TypeProduct_item
                Models.StockModel.DeleteAllTypeByProductId(id);
                Models.StockModel.DeleteTypeProduct(id);
                ViewData["Result"] = "Delete success!";
            }
            else
                ViewData["Result"] = "Type Product have product. You can't delete";

            return Redirect(returnUrl);
        }
        #endregion

        #region "Product"

        public ActionResult ChangeStatus(int? id, int? proid)
        {
            Models.StockModel.UpdateStatus(id, proid);

            string outStr = "" + proid;
            return Json(outStr);
        }

        [HttpPost]
        public JsonResult SaveAddProductItem(List<string> ids)
        {
            //string ProductName, string ProductDes, string Features, string Title, string MetaKeyword, 
            //string MetaDescription, int LanguagesID
            int itemID = 0;

            if (ids[6] != string.Empty && ids[6] != null)
            {
                SCSService.Product_Item item = new Product_Item();
                item.ProductName = ids[0].ToString();
                item.ProductDes = ids[1].ToString();
                item.Features = ids[2].ToString();
                item.LanguagesID = int.Parse(ids[6].ToString());
                item.ProductID = null;
                item.Title = ids[3].ToString();
                item.MetaKeyword = ids[4].ToString();
                item.MetaDescription = ids[5].ToString();

                itemID = Models.StockModel.CreateProductItem(item);
            }
            return Json(itemID);
        }

        [HttpPost]
        public JsonResult UpdateProductItem(List<string> ids)
        {
            //string ProductName, string ProductDes, string Features, string Title, string MetaKeyword, 
            //string MetaDescription,int ProductID, int LanguagesID,int ProductItemID
            //int itemID = 0;

            if (ids[8] != string.Empty && ids[8] != null)
            {
                SCSService.Product_Item item = Models.StockModel.GetProductItemByID(int.Parse(ids[8]));
                item.ProductName = ids[0].ToString();
                item.ProductDes = ids[1].ToString();
                item.Features = ids[2].ToString();
                item.Title = ids[3].ToString();
                item.MetaKeyword = ids[4].ToString();
                item.MetaDescription = ids[5].ToString();
                item.ProductID = int.Parse(ids[6].ToString());
                item.LanguagesID = int.Parse(ids[7].ToString());
                item.ProductItemID = int.Parse(ids[8].ToString());

                Models.StockModel.UpdateProductforItem(item);
            }
            return Json(1);
        }

        public JsonResult GetProductItemByLanguageIDandProductID(List<string> ids)
        {

            string languagesId = ids[0].ToString();
            string proId = ids[1].ToString();
            SCSService.Product_Item items = new Product_Item();
            if (proId != null && languagesId != null)
            {
                if (proId != string.Empty && languagesId != string.Empty)
                {
                    items = Models.StockModel.GetProductItemByLangIDandProductID(int.Parse(languagesId), int.Parse(proId));
                }

            }
            string result = "";

            if (items != null)
            {
                result += items.ProductItemID + "|";
                if (items.ProductName != null)
                {
                    result += items.ProductName + "|";
                }
                else
                {
                    result += "" + "|";
                }

                if (items.ProductDes != null)
                {
                    result += items.ProductDes + "|";
                }
                else
                {
                    result += "" + "|";
                }

                if (items.Features != null)
                {
                    result += items.Features + "|";
                }
                else
                {
                    result += "" + "|";
                }

                if (items.Title != null)
                {
                    result += items.Title + "|";
                }
                else
                {
                    result += "" + "|";
                }

                if (items.MetaKeyword != null)
                {
                    result += items.MetaKeyword + "|";
                }
                else
                {
                    result += "" + "|";
                }

                if (items.MetaDescription != null)
                {
                    result += items.MetaDescription + "|";
                }
                else
                {
                    result += "" + "|";
                }

            }
            ViewData["Content"] = items.ProductDes;
            return this.Json(result);

        }

        public ActionResult CreateProduct()
        {
            var product = new Models.Collection.ProductCollection();
            int siteGuid =GetSiteGuid();
            int languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());

            ViewData["IsAdd"] = true;

            ViewData["ListTypeProductDrop"] = new SelectList(GetListTypeProductDropBasic(null, null, null, null,null, StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter()), siteGuid), "TypeProductID", "TypeProductName");

            //ViewData["ListLanguage"] = new SelectList(Models.ModelsFontend.LanguageModel.GetListLanguageBySiteGuid(GetSiteGuid()), "LanguagesID", "countryName", languageId);
            ViewData["ListLanguage"] = new SelectList(Models.ModelsFontend.LanguageModel.GetListLanguageBySiteGuid(GetSiteGuid()), "LanguagesID", "countryName", languageId != null ? languageId : 0);
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("DetailProduct", product);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveAddProduct(FormCollection collection)
        {
            int languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            var product = new Models.Collection.ProductCollection();
            TryUpdateModel(product);
            int proID = 0;
            int manaID = 0;
            try
            {
                if (product.ArrTypeProductID != "")
                {
                    //Create Product
                    SCSService.Product pro = new Product();
                    pro.ProductName = product.ProductName;
                    pro.ProductDes = product.ProductDes;
                    pro.Status = 1;
                    pro.Images = product.Images;
                    pro.Features = product.Features;
                    pro.CreateDate = DateTime.Now;
                    pro.CreateUser = int.Parse(Session["UserID"].ToString());
                    pro.Title = product.Title != string.Empty ? product.Title : pro.ProductName;
                    pro.MetaKeyword = product.MetaKeyword;
                    pro.MetaDescription = product.MetaDescription;
                    pro.ProductCode = product.ProductCode;

                    proID = Models.StockModel.CreateProduct(pro);

                    if (proID > 0)
                    {
                        var arr = product.ArrTypeProductID.ToString().Split(',');
                        foreach (var item in arr)
                        {
                            if(!string.IsNullOrEmpty(item))
                            {
                            //Add Product to Type_Product_Manage
                            SCSService.Type_Product_Manage manage = new Type_Product_Manage();
                            manage.ProductID = proID;
                            manage.TypeProductID = int.Parse(item);
                            manage.Status = 1;

                            manaID = Models.StockModel.CreateManageTypeProduct(manage);
                            }
                        }
                    }

                    //Update List ProductItem
                    if (proID > 0)
                    {
                        if (product.ArrItemsID != null && product.ArrItemsID != "")
                        {
                            string[] arrItems = product.ArrItemsID.Split(',');

                            for (int i = 0; i < arrItems.Length; i++)
                            {
                                if (!string.IsNullOrEmpty(arrItems[i]))
                                {
                                    SCSService.Product_Item items = Models.StockModel.GetProductItemByID(int.Parse(arrItems[i].ToString()));
                                    items.ProductID = proID;

                                    Models.StockModel.UpdateProductforItem(items);
                                }
                            }
                        }     
                    }
                    //Create 1 Item source
                    Product_Item it = new Product_Item();
                    it.ProductName = product.ProductName;
                    it.ProductDes = product.ProductDes;
                    it.Features = product.Features;
                    it.Title = product.Title != string.Empty ? product.Title : pro.ProductName;
                    it.MetaKeyword = product.MetaKeyword;
                    it.MetaDescription = product.MetaDescription;
                    it.LanguagesID = languageId;
                    it.ProductID = proID;
                    StockModel.CreateProductItem(it);
                   

                    ViewData["Result"] = "Create Product Success!";

                    return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/Stock/ListProduct");
                }
                else
                {
                    ViewData["Result"] = "Please Choice Type Product!";
                    return View("DetailProduct", product);
                }

            }
            catch
            {
                return View("DetailProduct", new Models.Collection.ProductCollection());
            }

        }

        public ActionResult EditProduct(int id)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            

            var pro = Models.StockModel.GetProductByID(id);
            var product = new Models.Collection.ProductCollection();
            var listTypeID = Models.StockModel.GetListTypeProductIdManageByProductID(id);
           
            IEnumerable<int> seleteds = listTypeID.ToList();


            product.ProductName = pro.ProductName;
            product.ProductDes = pro.ProductDes;
            product.Images = pro.Images;
            product.ProductCode = pro.ProductCode;
            product.Status = pro.Status;
            if (pro.Status == 1)
                product.Active = true;
            else
            if (pro.Status == 0)
            product.Active = false;

            product.Features = pro.Features;
            product.CreateDate = pro.CreateDate;
            product.CreateUser = pro.CreateUser;
            product.ModifyDate = pro.ModifyDate;
            product.ModifyUser = pro.ModifyUser;
            product.ProductID = pro.ProductID;
            product.Title = pro.Title;
            product.MetaKeyword = pro.MetaKeyword;
            product.MetaDescription = pro.MetaDescription;
            product.ProductID = pro.ProductID;

            string arrId = "";
            foreach (var item in listTypeID)
            {
                arrId += item + ",";
            }
            product.ArrTypeProductID = arrId.Length > 1 ? arrId.Substring(0, arrId.LastIndexOf(',')) : "";
            ViewData["IsAdd"] = false;
            ViewData["ListLanguage"] = new SelectList(Models.ModelsFontend.LanguageModel.GetListLanguageBySiteGuid(GetSiteGuid()), "LanguagesID", "countryName", LanguageID != null ? LanguageID : 0);
            ViewData["ListTypeProductDrop"] = new MultiSelectList(GetListTypeProductDropBasic(null, null, null, null,null, StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter()), siteGuid), "TypeProductID", "TypeProductName");

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("DetailProduct", product);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveEditProduct(FormCollection collection)
        {
            var product = new Models.Collection.ProductCollection();
            TryUpdateModel(product);
            int siteGuid = GetSiteGuid();
            
            try
            {

                //Update Product
                SCSService.Product pro = Models.StockModel.GetProductByID(product.ProductID);
                pro.ProductName = product.ProductName;
                pro.ProductDes = product.ProductDes;
                pro.ProductCode = product.ProductCode;
                pro.Status = product.Active==true?(byte)1:(byte)0;
                pro.Images = product.Images;
                pro.Features = product.Features;
                pro.ModifyDate = DateTime.Now;
                pro.ModifyUser = int.Parse(Session["UserID"].ToString());
                pro.Title = product.Title;
                pro.MetaKeyword = product.MetaKeyword;
                pro.MetaDescription = product.MetaDescription;

                //Call Update method
                Models.StockModel.UpdateProduct(pro);

                //Update Ptoduct Manage
                //Check List . If type ptoduct in list Unchecked All ==> Not Update

                if (product.ArrTypeProductID != "")
                {
                    //Delete all Product in Type_Product_Manage
                    var list = Models.StockModel.GetListProductManageByProductID(pro.ProductID);
                    foreach (var item in list)
                    {
                        Models.StockModel.DeleteProductManage(item.ManageID);
                    }

                    //Create Product Type Manager New
                    int manaID = 0;

                    var arr = product.ArrTypeProductID.ToString().Split(',');
                    foreach (var item in arr)
                    {
                        if(!string.IsNullOrEmpty(item))
                        {
                        //Add Product to Type_Product_Manage
                        SCSService.Type_Product_Manage manage = new Type_Product_Manage();
                        manage.ProductID = pro.ProductID;
                        manage.TypeProductID = int.Parse(item);
                        manage.Status = 1;

                        manaID = Models.StockModel.CreateManageTypeProduct(manage);
                        }
                    }
                    ViewData["Result"] = "Update Product Success!";
                    return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/Stock/ListProduct/");
                }
                else
                {
                    ViewData["Result"] = "Update Product failed!";
                    return View("DetailProduct", product);
                }
            }
            catch
            {
                return View("DetailProduct", new Models.Collection.ProductCollection());
            }
            // return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/Stock/EditProduct/" + product.ProductID);
        }

        public Product_Price GetPriceProduct(int id, int? languageId, int? currencyID)
        {
            return Models.StockModel.GetLastProductPriceByProductId(id, (int)languageId, currencyID);
        }

        public long GetStockProduct(int id)
        {
            return Models.StockModel.GetProductStockByProductId(id);
        }

        public static string GetGridThClass(ViewDataDictionary<SCS.Core.ViewModels.ListProductViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] != sortField)
                return "";

            if ((string)viewData["SortDirection"] == "Asc")
                return "asc";

            return "desc";
        }

        public static string GetGridThOnClick(ViewDataDictionary<SCS.Core.ViewModels.ListProductViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] == sortField && (string)viewData["SortDirection"] == "Asc")
                return "sort('" + sortField + "', 'Desc');";

            return "sort('" + sortField + "', 'Asc');";
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ListProduct(int? id, string ProductNameSearch, string ProductCodeSearch)
        {
            //Id đầu vào là typeId
            int currentPage = 1;
            int pageSize = 2000;
            string sortField = "ProductID";
            string sortDirection = "Asc";

            int siteGuid = GetSiteGuid();
           

            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;


            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return ListProduct(ProductNameSearch, ProductCodeSearch, currentPage, pageSize, sortField, sortDirection, null, id, siteGuid);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult ListProduct(string ProductNameSearch, string ProductCodeSearch, int? currentPage, int? pageSize, string sortField, string sortDirection, string gridAction, int? id, int? siteGuid)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            //id đầu vào là typeId
            if (gridAction == "PageSizeChanged" || gridAction == "Sorted")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }


            if (pageSize == null)
            {
                pageSize = 2000;
            }

            if (siteGuid == null)
            {

                siteGuid = GetSiteGuid();

            }

            ViewData["currentPage"] = currentPage;


            var query = Models.StockModel.GetListProductByTypeProduct(ProductNameSearch, ProductCodeSearch, id, LanguageID, (int)siteGuid).AsQueryable();
            
            int totalRows = query.Count();

            if (!String.IsNullOrEmpty(sortField))
            {
                var param = Expression.Parameter(typeof(Product), "product");
                var sortExpression = Expression.Lambda<Func<Product, object>>
                                        (Expression.Convert(Expression.Property(param, sortField), typeof(object)), param);

                if (sortDirection == "DESC")
                    query = query.OrderBy(sortExpression);
                else
                    query = query.OrderByDescending(sortExpression);
            }

            int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            if (totalPages != 1)
            {
                //paging
                query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
            }


            UpdateSorterViewData(sortField, sortDirection);
            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize);

            var result = query.ToList();

            if (totalRows == 0)
                result = new List<SCSService.Product>();


            // Set up our ViewModel
            var viewModel = new ListProductViewModels
            {
                ProductItem = result,
                TypeProduct = id != null ? Models.StockModel.GetTypeProduct((int)id) : null,
                ProductNameSearch = ProductNameSearch,
                ProductCodeSearch = ProductCodeSearch
            };

            // Return the view
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View(viewModel);
        }
        public ActionResult DeleteProduct(int id, string returnUrl)
        {
            try
            {
            Models.StockModel.DeleteProductPriceByProductID(id);
            Models.StockModel.DeleteProduct(id);
            ViewData["Result"] = "Delete success!";

            return Redirect(returnUrl);
            }
            catch {

                return Redirect(returnUrl);
            }
        }
        #endregion

        #region "Properties"

        public List<Type_Property> GetListTypePropertyDrop(int LanguagesID, int siteGuid)
        {
            return Models.StockModel.GetListTypeProperty(LanguagesID, siteGuid);
        }

        public static string GetGridThClass(ViewDataDictionary<SCS.Core.ViewModels.ProductPropertiesViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] != sortField)
                return "";

            if ((string)viewData["SortDirection"] == "Asc")
                return "asc";

            return "desc";
        }

        public static string GetGridThOnClick(ViewDataDictionary<SCS.Core.ViewModels.ProductPropertiesViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] == sortField && (string)viewData["SortDirection"] == "Asc")
                return "sort('" + sortField + "', 'Desc');";

            return "sort('" + sortField + "', 'Asc');";
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ProductProperties(int? id, int? proid)
        {
            //Id đầu vào là typeId
            int currentPage = 1;
            int pageSize = 20;
            string sortField = "PropertiesID";
            string sortDirection = "Asc";

            int siteGuid = GetSiteGuid();
            
            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;

            ViewData["ProductTypePropertiesID"] = StockModel.GetProductTypePropertiesByProIDandTypeProPerId(proid??0,id??0)!=null?StockModel.GetProductTypePropertiesByProIDandTypeProPerId(proid??0,id??0).ProductTypePropertiesID:0;
            ViewData["ProductID"] = proid ?? 0;
            ViewData["TypePropertiesID"] = id ?? 0;

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return ProductProperties(currentPage, pageSize, sortField, sortDirection, null, id, proid, siteGuid);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult ProductProperties(int? currentPage, int? pageSize, string sortField, string sortDirection, string gridAction, int? id, int? proid, int? siteGuid)
        {
            ViewData["ProductTypePropertiesID"] = StockModel.GetProductTypePropertiesByProIDandTypeProPerId(proid ?? 0, id ?? 0) != null ? StockModel.GetProductTypePropertiesByProIDandTypeProPerId(proid ?? 0, id ?? 0).ProductTypePropertiesID : 0;
            ViewData["ProductID"] = proid ?? 0;
            ViewData["TypePropertiesID"] = id ?? 0;

            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            //id đầu vào là typeId
            if (gridAction == "PageSizeChanged" || gridAction == "Sorted")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }


            if (pageSize == null)
            {
                pageSize = 20;
            }

            if (siteGuid == null)
            {
                siteGuid = GetSiteGuid();
            }

            ViewData["currentPage"] = currentPage;

            var query = Models.StockModel.GetListProductPropertyByType(id, proid).AsQueryable();
            int totalRows = query.Count();

            if (!String.IsNullOrEmpty(sortField))
            {
                var param = Expression.Parameter(typeof(Product_Property), "productProperty");
                var sortExpression = Expression.Lambda<Func<Product_Property, object>>
                                        (Expression.Convert(Expression.Property(param, sortField), typeof(object)), param);

                if (sortDirection == "Asc")
                    query = query.OrderBy(sortExpression);
                else
                    query = query.OrderByDescending(sortExpression);
            }

            int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            if (totalPages != 1)
            {
                //paging
                query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
            }


            UpdateSorterViewData(sortField, sortDirection);
            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize);

            var result = query.ToList();

            if (totalRows == 0)
                result = new List<SCSService.Product_Property>();


            //// Set up our ViewModel
            var viewModel = new ProductPropertiesViewModels
            {
                PropertyItem = result,
                Product = proid != null ? Models.StockModel.GetProductByID((int)proid) : null,
                TypeProperties = id != null ? Models.StockModel.GetTypePropertiesById((int)id) : null
            };

            //// Return the view
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View(viewModel);
            //return View(result);
        }

        public static string GetGridThClass(ViewDataDictionary<SCS.Core.ViewModels.ProductTypePropertyManageViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] != sortField)
                return "";

            if ((string)viewData["SortDirection"] == "Asc")
                return "asc";

            return "desc";
        }

        public static string GetGridThOnClick(ViewDataDictionary<SCS.Core.ViewModels.ProductTypePropertyManageViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] == sortField && (string)viewData["SortDirection"] == "Asc")
                return "sort('" + sortField + "', 'Desc');";

            return "sort('" + sortField + "', 'Asc');";
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ProductTypeProperties(int? id)
        {
            //Id đầu vào là proId
            int currentPage = 1;
            int pageSize = 2000;
            string sortField = "ProductTypePropertiesID";
            string sortDirection = "Asc";

            int siteGuid = GetSiteGuid();
            

            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;
            ViewData["ListTypeProduct"] = new SelectList(GetListTypePropertyDrop(StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter()), siteGuid), "TypePropertiesID", "TypePropertiesName");

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return ProductTypeProperties(currentPage, pageSize, sortField, sortDirection, null, id, siteGuid);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult ProductTypeProperties(int? currentPage, int? pageSize, string sortField, string sortDirection, string gridAction, int? id, int? siteGuid)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            //id đầu vào là proId
            if (gridAction == "PageSizeChanged" || gridAction == "Sorted")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }


            if (pageSize == null)
            {
                pageSize = 2000;
            }

            if (siteGuid == null)
            {

                if (Request.Url.Host == "localhost")
                {
                    if (Request.Url.ToString().Contains("favicon.ico"))
                    {

                    }
                    else
                        siteGuid = DefaultSiteGuidGetter();
                }
                else
                {
                    siteGuid = ConfigModel.GetWebsitebyDomain(Request.Url.Host).SiteGuid;
                }

            }

            ViewData["currentPage"] = currentPage;
            ViewData["ListTypeProduct"] = new SelectList(GetListTypePropertyDrop(StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter()), (int)siteGuid), "TypePropertiesID", "TypePropertiesName");

            var query = Models.StockModel.GetListProductTypePropertyByProductID((int)id).AsQueryable();
            int totalRows = query.Count();

            if (!String.IsNullOrEmpty(sortField))
            {
                var param = Expression.Parameter(typeof(Product_Type_Property), "Product_Type_Property");
                var sortExpression = Expression.Lambda<Func<Product_Type_Property, object>>
                                        (Expression.Convert(Expression.Property(param, sortField), typeof(object)), param);

                if (sortDirection == "Asc")
                    query = query.OrderBy(sortExpression);
                else
                    query = query.OrderByDescending(sortExpression);
            }

            int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            if (totalPages != 1)
            {
                //paging
                query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
            }


            UpdateSorterViewData(sortField, sortDirection);
            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize);

            var result = query.ToList();

            if (totalRows == 0)
                result = new List<SCSService.Product_Type_Property>();


            //// Set up our ViewModel
            var viewModel = new ProductTypePropertyManageViewModels
            {
                ProductTypePropertyItem = result,
                Product = id != null ? Models.StockModel.GetProductByID((int)id) : null
            };

            //// Return the view
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View(viewModel);
            //return View(result);
        }

        public ActionResult AddProductTypeProperties(int? id)
        {
            var poductTypeProperty = new SCS.Core.Models.Collection.ProductTypePropertyCollection();
            poductTypeProperty.ProductID = id;

            int siteGuid = GetSiteGuid();

            int languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());

            ViewData["IsAdd"] = true;
            ViewData["ListTypeProduct"] = new SelectList(GetListTypePropertyDrop(StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter()), siteGuid), "TypePropertiesID", "TypePropertiesName");

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("DetailProductTypeProperties", poductTypeProperty);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveAddProductTypeProperties(FormCollection collection)
        {
            var poductTypeProperty = new SCS.Core.Models.Collection.ProductTypePropertyCollection();
            TryUpdateModel(poductTypeProperty);
            int typeId = 0;
            try
            {

                //Create Type Product
                SCSService.Product_Type_Property ptp = new Product_Type_Property();
                if (poductTypeProperty.TypePropertiesID != null)
                {
                    ptp.TypePropertiesID = poductTypeProperty.TypePropertiesID;
                    ptp.ProductID = poductTypeProperty.ProductID;
                    ptp.Status = poductTypeProperty.Status;
                    
                    typeId = Models.StockModel.CreateProductTypeProperty(ptp);

                    ViewData["Result"] = "Create ProductTypeProperty Success!";
                }              
            }
            catch
            {
               
            }
            return RedirectToAction("ProductTypeProperties", new { id = poductTypeProperty.ProductID });
        }

        public ActionResult CreateProductProperties(int? id, int? proid, int? typeProperid)
        {
            //id la id cua ProductTypePropertiesID
            var productProperty = new Models.Collection.ProductPropertiesCollection();
            productProperty.ProductTypePropertiesID = id;

            if (proid != null)
            {
                var pro = StockModel.GetProductByID(proid??0);
                ViewData["ProductName"] = pro.ProductName;
            }

            if (typeProperid != null)
            {
                var type = StockModel.GetTypePropertiesById(typeProperid??0);
                ViewData["TypePropertiesName"] = type.TypePropertiesName;
            }

            ViewData["IsAdd"] = true;
            
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("DetailProductProperties", productProperty);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveAddProductProperties(FormCollection collection)
        {
            var productProperty = new Models.Collection.ProductPropertiesCollection();
            TryUpdateModel(productProperty);

            int proID = 0;
           
            try
            {
                if (productProperty.ProductTypePropertiesID != null && productProperty.ProductTypePropertiesID!=0)
                {
                    //Create ProductProperties
                    SCSService.Product_Property pro = new Product_Property();
                    pro.PropertiesName = productProperty.PropertiesName;
                    pro.PropertiesDes = productProperty.PropertiesDes;
                    pro.Status = 1;
                    pro.Images = productProperty.Images;
                    pro.ProductTypePropertiesID = productProperty.ProductTypePropertiesID;
                   
                    proID = Models.StockModel.CreateProductProperties(pro);
                                        
                    ViewData["Result"] = "Create ProductProperties Success!";

                    return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/Stock/ProductProperties/" + productProperty.ProductTypePropertiesID);
                }
                else
                {
                    return View("DetailProductProperties", productProperty);
                }

            }
            catch
            {
                return View("DetailProductProperties", new Models.Collection.ProductPropertiesCollection());
            }

        }

        public ActionResult EditProductProperties(int id)
        {
          
            var pro = Models.StockModel.GetProductPropertiesByID(id);
            var productProperty = new Models.Collection.ProductPropertiesCollection();

            productProperty.PropertiesID = pro.PropertiesID;
            productProperty.ProductTypePropertiesID = pro.ProductTypePropertiesID;
            productProperty.Images = pro.Images;
            productProperty.PropertiesName = pro.PropertiesName;
            productProperty.PropertiesDes = pro.PropertiesDes;
            productProperty.Status = pro.Status;
            
            ViewData["IsAdd"] = false;

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("DetailProductProperties", productProperty);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveEditProductProperties(FormCollection collection)
        {
            var productProperty = new Models.Collection.ProductPropertiesCollection();
            TryUpdateModel(productProperty);
            
            try
            {

                //Update ProductProperties
                SCSService.Product_Property pro = Models.StockModel.GetProductPropertiesByID(productProperty.PropertiesID??0);
                pro.PropertiesName = productProperty.PropertiesName;
                pro.PropertiesDes = productProperty.PropertiesDes;
                pro.ProductTypePropertiesID = productProperty.ProductTypePropertiesID;
                pro.Status = productProperty.Status;
                pro.Images = productProperty.Images;
               
                //Call Update method
                Models.StockModel.UpdateProductProperties(pro);

                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/Stock/ProductProperties/" + productProperty.ProductTypePropertiesID);
            }
            catch
            {
                return View("DetailProductProperties", new Models.Collection.ProductPropertiesCollection());
            }
           
        }
        #endregion

        #region "ProductPrice"
        public ActionResult ChangeStatusPriceManage(int? id, int? proid)
        {
            Models.StockModel.UpdateStatusPrice(id, proid);

            string outStr = "" + proid;
            return Json(outStr);
        }

        public static string GetGridThClass(ViewDataDictionary<SCS.Core.ViewModels.PriceManageViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] != sortField)
                return "";

            if ((string)viewData["SortDirection"] == "Asc")
                return "asc";

            return "desc";
        }

        public static string GetGridThOnClick(ViewDataDictionary<SCS.Core.ViewModels.PriceManageViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] == sortField && (string)viewData["SortDirection"] == "Asc")
                return "sort('" + sortField + "', 'Desc');";

            return "sort('" + sortField + "', 'Asc');";
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult PriceManage(int? id, DateTime? StartDateSearch, DateTime? EndDateSearch, float? ValueSearch, int? StatusSearch)
        {
            int currentPage = 1;
            int pageSize = 2000;
            string sortField = "PriceID";
            string sortDirection = "Asc";

            int siteGuid =GetSiteGuid();
            
            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return PriceManage(currentPage, pageSize, sortField, sortDirection, null, id, StartDateSearch, EndDateSearch, ValueSearch, StatusSearch, siteGuid);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult PriceManage(int? currentPage, int? pageSize, string sortField, string sortDirection, string gridAction, int? id, DateTime? StartDateSearch, DateTime? EndDateSearch, float? ValueSearch, int? StatusSearch, int? siteGuid)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            //id đầu vào là proid
            if (gridAction == "PageSizeChanged" || gridAction == "Sorted")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }

            if (pageSize == null)
            {
                pageSize = 2000;
            }

            if (siteGuid == null)
            {
                siteGuid = GetSiteGuid();
            }

            ViewData["currentPage"] = currentPage;

            var query = Models.StockModel.GetListProductPriceByProductId((int)id, LanguageID, StartDateSearch, EndDateSearch, ValueSearch, StatusSearch).AsQueryable();
            int totalRows = query.Count();

            if (!String.IsNullOrEmpty(sortField))
            {
                var param = Expression.Parameter(typeof(Product_Price), "ProductPrice");
                var sortExpression = Expression.Lambda<Func<Product_Price, object>>
                                        (Expression.Convert(Expression.Property(param, sortField), typeof(object)), param);

                if (sortDirection == "Asc")
                    query = query.OrderBy(sortExpression);
                else
                    query = query.OrderByDescending(sortExpression);
            }

            int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            if (totalPages != 1)
            {
                //paging
                query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
            }


            UpdateSorterViewData(sortField, sortDirection);
            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize);

            var result = query.ToList();

            if (totalRows == 0)
                result = new List<SCSService.Product_Price>();


            //// Set up our ViewModel
            var viewModel = new PriceManageViewModels
            {
                ProductPriceList = result,
                Product = id != null ? Models.StockModel.GetProductByID((int)id) : null,
                ValueSearch = ValueSearch,
                StartDateSearch = StartDateSearch,
                EndDateSearch = EndDateSearch

            };

            //// Return the view
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View(viewModel);
            //return View(result);
        }

        public ActionResult CreatePrice(int? id)
        {
            var price = new Models.Collection.PriceCollection();
            int siteGuid = GetSiteGuid();
            
            int languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());

            price.ProductID = id;
            price.LanguagesID = languageId;

            ViewData["IsAdd"] = true;
            ViewData["ListCurrencyDrop"] = new SelectList(StockModel.GetListCurrency(), "CurrencyID", "CurrencyCode");


            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("DetailPrice", price);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult SaveAddPrice(FormCollection collection)
        {
            var price = new Models.Collection.PriceCollection();
            TryUpdateModel(price);
            int priceId = 0;
            try
            {
                if (price.ProductID != null)
                {
                    price.StartDate = Convert.ToDateTime(Request.Form["StartDate"], new System.Globalization.CultureInfo("vi-VN"));
                    price.EndDate = Convert.ToDateTime(Request.Form["EndDate"], new System.Globalization.CultureInfo("vi-VN"));
                    SCSService.Product_Price pri = new Product_Price();
                    pri.PriceValue = price.PriceValue;
                    pri.StartDate = price.StartDate;
                    pri.EndDate = price.EndDate;
                    pri.Notes = price.Notes;
                    pri.ProductID = price.ProductID;
                    pri.LanguagesID = price.LanguagesID;
                    pri.CurrencyID = price.CurrencyID;
                    if (price.Status != null)
                    {
                        if (price.Status == true)
                            pri.Satus = 1;
                        else
                            pri.Satus = 0;
                    }

                    priceId = Models.StockModel.CreatePrice(pri);

                    ViewData["Result"] = "Create Price Success!";

                    return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/Stock/PriceManage/" + price.ProductID);
                }
                else
                {
                    return View("DetailPrice", price);
                }

            }
            catch
            {
                return View("DetailPrice", new Models.Collection.PriceCollection());
            }

        }

        public ActionResult EditPrice(int id)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            
            var pri = Models.StockModel.GetProductPriceByID((int)id);
            var price = new Models.Collection.PriceCollection();

            price.PriceValue = pri.PriceValue != null ? (float)pri.PriceValue : 0;
            price.StartDate = pri.StartDate;
            price.EndDate = pri.EndDate;
            price.Notes = pri.Notes;
            price.ProductID = pri.ProductID;
            price.LanguagesID = pri.LanguagesID;
            price.CurrencyID = pri.CurrencyID;
            if (pri.Satus == 1)
            {
                price.Status = true;
            }
            else if (pri.Satus == 0)
            {
                price.Status = false;
            }

            price.PriceID = pri.PriceID;

            ViewData["IsAdd"] = false;

            ViewData["ListCurrencyDrop"] = new SelectList(StockModel.GetListCurrency(), "CurrencyID", "CurrencyCode");

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("DetailPrice", price);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveEditPrice(FormCollection collection)
        {
            var price = new Models.Collection.PriceCollection();
            TryUpdateModel(price);
            int siteGuid = GetSiteGuid();
            
            try
            {
                //Update Price
                price.StartDate = Convert.ToDateTime(Request.Form["StartDate"], new System.Globalization.CultureInfo("vi-VN"));
                price.EndDate = Convert.ToDateTime(Request.Form["EndDate"], new System.Globalization.CultureInfo("vi-VN"));
                SCSService.Product_Price pri = Models.StockModel.GetProductPriceByID((int)price.PriceID);

                pri.PriceValue = price.PriceValue;
                pri.StartDate = price.StartDate;
                pri.EndDate = price.EndDate;
                pri.Notes = price.Notes;
                pri.LanguagesID = price.LanguagesID;
                pri.CurrencyID = price.CurrencyID;
                pri.ProductID = price.ProductID;
                pri.Satus = price.Status == true ? (byte)1 : (byte)0;
                //Update Product Price
                Models.StockModel.UpdateProductPrice(pri);
               
                //return View("DetailPrice", pri);
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/Stock/PriceManage/" + price.ProductID.ToString());
            }
            catch
            {
                return View("DetailPrice", new Models.Collection.PriceCollection());
            }
            
        }

        public ActionResult DeletePrice(int id, string returnUrl)
        {

            Models.StockModel.DeleteProductPrice(id);
            ViewData["Result"] = "Delete success!";

            return Redirect(returnUrl);
        }
        #endregion

        #region "Discount"
        public ActionResult CreateDiscount()
        {
            var discount = new Models.Collection.DiscountCollection();
            int siteGuid = GetSiteGuid();
            
            int languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());


            ViewData["IsAdd"] = true;
            ViewData["ListTypeProductDrop"] = new SelectList(GetListTypeProductDropBasic(null, null, null, null,null, StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter()), siteGuid), "TypeProductID", "TypeProductName");


            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("DetailDiscount", discount);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveAddDiscount(FormCollection collection)
        {
            var discount = new Models.Collection.DiscountCollection();
            TryUpdateModel(discount);
            int languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            discount.StartDate = Convert.ToDateTime(Request.Form["StartDate"], new System.Globalization.CultureInfo("vi-VN"));
            discount.EndDate = Convert.ToDateTime(Request.Form["EndDate"], new System.Globalization.CultureInfo("vi-VN"));
            if (discount.StartDate != null)
            {
                if (discount.EndDate != null)
                {
                    if ((DateTime)discount.StartDate >= (DateTime)discount.EndDate)
                    {
                        ViewData["Result"] = "StartDate can't lager more than EndDate";
                        return View("DetailDiscount", discount);
                    }
                }
            }
            else
            {
                ViewData["Result"] = "Please choice StartDate for discount!";
                return View("DetailDiscount", new Models.Collection.DiscountCollection());
            }


            if (discount.TypeDiscounts == true)
            {
                //Percent
                if (discount.DiscountPercent == null)
                {
                    ViewData["Result"] = "Please enter percent number for discount!";
                    return View("DetailDiscount", discount);
                }
            }
            else
            {
                //Value
                if (discount.DiscountValue == null)
                {
                    ViewData["Result"] = "Please enter value number for discount!";
                    return View("DetailDiscount", discount);
                }
            }

            int discountID = 0;
            try
            {
                if (discount.ArrProductID != "")
                {
                    SCSService.Discount dis = new Discount();
                    dis.TypeDiscounts = discount.TypeDiscounts;
                    dis.StartDate = discount.StartDate;
                    dis.EndDate = discount.EndDate;
                    dis.DiscountPercent = discount.DiscountPercent;
                    dis.DiscountValue = discount.DiscountValue;
                    if (discount.Status != null)
                    {
                        if (discount.Status == true)
                            dis.Status = 1;
                        else
                            dis.Status = 0;
                    }
                    dis.Description = discount.Description;
                    dis.LanguagesID = languageId;
                    dis.SiteGuid = DefaultSiteGuidGetter();

                    discountID = Models.StockModel.CreateDiscount(dis);

                    if (discountID > 0)
                    {
                        var arrProductID = discount.ArrProductID.Split(',');
                        foreach (var item in arrProductID)
                        {
                            //Create Discount_Product_Manage
                            SCSService.Discount_Product_Manager manage = new Discount_Product_Manager();
                            manage.ProductID = int.Parse(item);
                            manage.DiscountsID = discountID;
                            manage.Status = 1;

                            Models.StockModel.CreateDiscountManage(manage);
                        }
                    }
                    ViewData["Result"] = "Create Discount Success!";
                    return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/Stock/DiscountManage");
                }
                else
                {
                    //ViewData["Result"] = "Please Choice Type Product!";
                    return View("DetailDiscount", discount);
                }
            }
            catch
            {
                return View("DetailDiscount", discount);
            }
        }

        public ActionResult EditDiscount(int id)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            
            var dis = Models.StockModel.GetDiscountByID((int)id);
            var discount = new Models.Collection.DiscountCollection();
            var listProductID = Models.StockModel.GetListProductByManageDiscountID(id);
            IEnumerable<int> seleteds = listProductID.ToList();

            discount.TypeDiscounts = dis.TypeDiscounts;
            discount.StartDate =dis.StartDate;
            discount.EndDate = dis.EndDate;
            discount.DiscountPercent = dis.DiscountPercent;
            discount.DiscountValue = dis.DiscountValue;
            if (dis.Status != null)
            {
                if (dis.Status == 1)
                    discount.Status = true;
                else
                    discount.Status = false;
            }

            discount.Description = dis.Description;
            discount.DiscountsID = dis.DiscountsID;

            string arrId = "";
            foreach (var item in listProductID)
            {
                arrId += item + ",";
            }
            discount.ArrProductID = arrId.Length > 1 ? arrId.Substring(0, arrId.LastIndexOf(',')) : "";

            var listTypeProductID = Models.StockModel.GetListTypeProductByListProductID(listProductID);
            string arrTypeId = "";
            foreach (var item in listTypeProductID)
            {
                arrTypeId += item + ",";
            }
            discount.ArrTypeProductID = arrTypeId.Length > 1 ? arrTypeId.Substring(0, arrTypeId.LastIndexOf(',')) : "";

            ViewData["IsAdd"] = false;

            ViewData["ListTypeProductDrop"] = new MultiSelectList(GetListTypeProductDropBasic(null, null, null, null,null, StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter()), siteGuid), "TypeProductID", "TypeProductName");


            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("DetailDiscount", discount);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveEditDiscount(FormCollection collection)
        {
            var discount = new Models.Collection.DiscountCollection();
            TryUpdateModel(discount);
            int siteGuid = GetSiteGuid();           
            try
            {
                //Update Discount
                discount.StartDate = Convert.ToDateTime(Request.Form["StartDate"], new System.Globalization.CultureInfo("vi-VN"));
                discount.EndDate = Convert.ToDateTime(Request.Form["EndDate"], new System.Globalization.CultureInfo("vi-VN"));
                SCSService.Discount dis = Models.StockModel.GetDiscountByID((int)discount.DiscountsID);

                dis.TypeDiscounts = discount.TypeDiscounts;
                dis.StartDate = discount.StartDate;
                dis.EndDate = discount.EndDate;
                dis.DiscountPercent = discount.DiscountPercent;
                dis.DiscountValue = discount.DiscountValue;
                dis.Description = discount.Description;
                dis.Status = discount.Status == true ? (byte)1 : (byte)0;
                ViewData["IsAdd"] = false;
                ViewData["ListTypeProductDrop"] = new MultiSelectList(GetListTypeProductDropBasic(null, null, null, null, null, StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter()), siteGuid), "TypeProductID", "TypeProductName");
                //Call Update method
                Models.StockModel.UpdateDiscount(dis);

                //Update Discount Ptoduct Manage
                //Check List . If type ptoduct in list Unchecked All ==> Not Update

                if (discount.ArrTypeProductID != "")
                {
                    if (discount.ArrProductID != "")
                    {
                        //Delete all Product in Discount_Product_Manage
                        var list = Models.StockModel.GetListProductManageByDiscountID(dis.DiscountsID);
                        foreach (var item in list)
                        {
                            Models.StockModel.DeleteProductManageDiscount(item.DiscountsID, item.ProductID);
                        }

                        //Create Discount_Product_Manage New

                        var arr = discount.ArrProductID.ToString().Split(',');
                        foreach (var item in arr)
                        {
                            //Add Product to Type_Product_Manage
                            SCSService.Discount_Product_Manager manage = new Discount_Product_Manager();
                            manage.DiscountsID = dis.DiscountsID;
                            manage.ProductID = int.Parse(item);
                            manage.Status = 1;

                            Models.StockModel.CreateDiscountManage(manage);
                        }
                        ViewData["Result"] = "Update Discount Success!";
                        return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/Stock/DiscountManage" );
                    }
                    else
                    {
                        ViewData["Result"] = "Please let's choice Product for discount.";
                        return View("DetailDiscount", discount);
                    }
                }
                else
                {
                    ViewData["Result"] = "Please let's choice type of Product for discount.";
                    return View("DetailDiscount", discount);
                }
            }
            catch
            {
                return View("DetailDiscount", new Models.Collection.DiscountCollection());
            }
        }

        public ActionResult GetListProductDropSelect(List<int> listTypeId)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            
            List<Product> listPro = new List<Product>();
            foreach (var item in listTypeId)
            {
                var listItem = Models.StockModel.GetListProductByTypeProduct(null, null, item, LanguageID, siteGuid);
                foreach (var i in listItem)
                {
                    listPro.Add(i);
                }
            }

            string arr = "";
            foreach (var item in listPro)
            {
                arr += item.ProductID + ",";
            }
            string outStr = arr.Length > 1 ? arr.Substring(0, arr.LastIndexOf(',')) : "";

            return Json(outStr);
        }

        public JsonResult GetListProductByListType(string id)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();

            if (id != null && id != string.Empty)
            {
                if (id.Contains(','))
                {
                    var arr = id.Split(',');

                    List<Product> listPro = new List<Product>();
                    foreach (var item in arr)
                    {
                        if (!string.IsNullOrEmpty(item))
                        {
                        var listItem = Models.StockModel.GetListProductByTypeProduct(null, null, int.Parse(item), LanguageID, siteGuid);
                        foreach (var i in listItem)
                        {
                            listPro.Add(i);
                        }
                        }
                    }
                    var listresult = listPro.Select(d => d.ProductID.ToString() + "|" + d.ProductName).Distinct().ToList();

                    return this.Json(listresult);
                }
                else
                    return this.Json("");
            }
            else
                return this.Json("");

        }

        public static string GetGridThClass(ViewDataDictionary<SCS.Core.ViewModels.DiscountManageViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] != sortField)
                return "";

            if ((string)viewData["SortDirection"] == "Asc")
                return "asc";

            return "desc";
        }

        public static string GetGridThOnClick(ViewDataDictionary<SCS.Core.ViewModels.DiscountManageViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] == sortField && (string)viewData["SortDirection"] == "Asc")
                return "sort('" + sortField + "', 'Desc');";

            return "sort('" + sortField + "', 'Asc');";
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult DiscountManage(int? id, DateTime? StartDateSearch, DateTime? EndDateSearch, int? ValueSearch, int? StatusSearch, int? TypeDiscounts)
        {
            int currentPage = 1;
            int pageSize = 20;
            string sortField = "DiscountsID";
            string sortDirection = "Asc";
            int siteGuid = GetSiteGuid();
            
            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return DiscountManage(currentPage, pageSize, sortField, sortDirection, null, id, StartDateSearch, EndDateSearch, ValueSearch, StatusSearch, TypeDiscounts, siteGuid);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult DiscountManage(int? currentPage, int? pageSize, string sortField, string sortDirection, string gridAction, int? id, DateTime? StartDateSearch, DateTime? EndDateSearch, int? ValueSearch, int? StatusSearch, int? TypeDiscounts, int? siteGuid)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            //id là mã product
            if (gridAction == "PageSizeChanged" || gridAction == "Sorted")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }


            if (pageSize == null)
            {
                pageSize = 20;
            }

            if (siteGuid == null)
            {
                siteGuid = GetSiteGuid();                
            }

            ViewData["currentPage"] = currentPage;

            var query = Models.StockModel.GetListDiscountManagerByProductID(id, LanguageID, StartDateSearch, EndDateSearch, ValueSearch, StatusSearch, TypeDiscounts).AsQueryable();
            int totalRows = query.Count();

            if (!String.IsNullOrEmpty(sortField))
            {
                var param = Expression.Parameter(typeof(Discount), "Discount");
                var sortExpression = Expression.Lambda<Func<Discount, object>>
                                        (Expression.Convert(Expression.Property(param, sortField), typeof(object)), param);

                if (sortDirection == "Asc")
                    query = query.OrderBy(sortExpression);
                else
                    query = query.OrderByDescending(sortExpression);
            }

            int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            if (totalPages != 1)
            {
                //paging
                query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
            }


            UpdateSorterViewData(sortField, sortDirection);
            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize);

            var result = query.ToList();

            if (totalRows == 0)
                result = new List<SCSService.Discount>();


            //// Set up our ViewModel
            var viewModel = new DiscountManageViewModels
            {
                DiscountList = result,
                Product = id != null ? Models.StockModel.GetProductByID((int)id) : null,
                ValueSearch = ValueSearch,
                StartDateSearch = StartDateSearch,
                EndDateSearch = EndDateSearch,
                TypeDiscounts = TypeDiscounts

            };

            //// Return the view
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View(viewModel);
            //return View(result);
        }

        public ActionResult ChangeStatusDiscount(int? id, int? proid)
        {
            Models.StockModel.UpdateStatusDiscount(id, proid);

            string outStr = "" + proid;
            return Json(outStr);
        }

        public ActionResult DeleteDiscount(int id, string returnUrl)
        {

            Models.StockModel.DeleteDiscount(id);
            ViewData["Result"] = "Delete success!";

            return Redirect(returnUrl);
        }
        #endregion

        #region "Stock"
        public static string GetGridThClass(ViewDataDictionary<SCS.Core.ViewModels.StockProductViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] != sortField)
                return "";

            if ((string)viewData["SortDirection"] == "Asc")
                return "asc";

            return "desc";
        }

        public static string GetGridThOnClick(ViewDataDictionary<SCS.Core.ViewModels.StockProductViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] == sortField && (string)viewData["SortDirection"] == "Asc")
                return "sort('" + sortField + "', 'Desc');";

            return "sort('" + sortField + "', 'Asc');";
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult StockManage(int? id, DateTime? StockInSearch, DateTime? ModifyDateSearch, long? QuantitySearch, int? StatusSearch)
        {
            int currentPage = 1;
            int pageSize = 2000;
            string sortField = "StockID";
            string sortDirection = "Asc";
            int siteGuid = GetSiteGuid();
            
            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return StockManage(currentPage, pageSize, sortField, sortDirection, null, id, StockInSearch, ModifyDateSearch, QuantitySearch, StatusSearch, siteGuid);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult StockManage(int? currentPage, int? pageSize, string sortField, string sortDirection, string gridAction, int? id, DateTime? StockInSearch, DateTime? ModifyDateSearch, long? QuantitySearch, int? StatusSearch, int? siteGuid)
        {
            //int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            //id đầu vào là proid
            if (gridAction == "PageSizeChanged" || gridAction == "Sorted")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }


            if (pageSize == null)
            {
                pageSize = 2000;
            }

            if (siteGuid == null)
            {
                siteGuid = GetSiteGuid();
            }

            ViewData["currentPage"] = currentPage;

            var query = Models.StockModel.GetListProductStockByProductId((int)id, StockInSearch, ModifyDateSearch, QuantitySearch, StatusSearch).AsQueryable();
            int totalRows = query.Count();

            if (!String.IsNullOrEmpty(sortField))
            {
                var param = Expression.Parameter(typeof(Product_Stock), "Product_Stock");
                var sortExpression = Expression.Lambda<Func<Product_Stock, object>>
                                        (Expression.Convert(Expression.Property(param, sortField), typeof(object)), param);

                if (sortDirection == "Asc")
                    query = query.OrderBy(sortExpression);
                else
                    query = query.OrderByDescending(sortExpression);
            }

            int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            if (totalPages != 1)
            {
                //paging
                query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
            }


            UpdateSorterViewData(sortField, sortDirection);
            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize);

            var result = query.ToList();

            if (totalRows == 0)
                result = new List<SCSService.Product_Stock>();


            //// Set up our ViewModel
            var viewModel = new StockProductViewModels
            {
                ProductStockList = result,
                Product = id != null ? Models.StockModel.GetProductByID((int)id) : null,
                QuantitySearch = QuantitySearch,
                StockInSearch = StockInSearch,
                ModifyDateSearch = ModifyDateSearch,
                StatusSearch = StatusSearch

            };

            //// Return the view
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View(viewModel);
            //return View(result);
        }

        public ActionResult CreateStock(int? id)
        {
            var sto = new Models.Collection.StockCollection();
            int siteGuid = GetSiteGuid();           

            int languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());

            sto.ProductID = id;

            ViewData["IsAdd"] = true;

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("DetailStock", sto);
        }

        //[AcceptVerbs(HttpVerbs.Post)]
        //[ValidateInput(false)]
        //public ActionResult SaveAddStock(FormCollection collection)
        //{
        //    var sto = new Models.Collection.StockCollection();
        //    TryUpdateModel(sto);
        //    int stockID = 0;
        //    try
        //    {
        //        if (sto.ProductID != null)
        //        {
        //            SCSService.Product_Stock stock = new Product_Stock();
        //            stock.Quantity = sto.Quantity;
        //            stock.StockCode = sto.StockCode;
        //            stock.StockIn = sto.StockIn;
        //            stock.ModifyDate = sto.ModifyDate;
        //            stock.NotesStock = sto.NotesStock;
        //            stock.ProductID = sto.ProductID;
        //            if (sto.Status != null)
        //            {
        //                if (sto.Status == true)
        //                    stock.Status = 1;
        //                else
        //                    stock.Status = 0;
        //            }


        //            stockID = Models.StockModel.CreateStock(stock);

        //            ViewData["Result"] = "Create Stock Success!";

        //            return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/Stock/StockManage/" + stockID);
        //        }
        //        else
        //        {
        //            return View("DetailStock", sto);
        //        }

        //    }
        //    catch
        //    {
        //        return View("DetailStock", new Models.Collection.StockCollection());
        //    }

        //}
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveAddStock(FormCollection collection)
        {
            var sto = new Models.Collection.StockCollection();
            TryUpdateModel(sto);
            int stockID = 0;
            int Pro_StockID = 0;
            int Pro_Stock_Detail = 0;
            string txtSerial = "";
            string txtCode = "";

            try
            {
                if (sto.ProductID != null)
                {
                    SCSService.Product_Stock stock = new Product_Stock();
                    stock.Quantity = sto.Quantity;
                    stock.StockCode = sto.StockCode;

                    stock.StockIn = sto.StockIn;
                    stock.NotesStock = sto.NotesStock;
                    if (sto.Status != null)
                    {
                        if (sto.Status == true)
                            stock.Status = 1;
                        else
                            stock.Status = 0;
                    }
                    //add Product to Product_stock
                    if (sto.ProductID > 0)
                    {

                        stock.ProductID = sto.ProductID;
                        if (!string.IsNullOrEmpty(Request.Form["Quantity"].ToString()))
                        {
                            stock.Quantity = long.Parse(Request.Form["Quantity"].ToString());
                        }
                        Pro_StockID = Models.StockModel.CreateStock(stock);
                    }
                    if (Pro_StockID > 0)
                    {

                        for (int i = 0; i < int.Parse(Request.Form["Quantity"].ToString()); i++)
                        {
                            SCSService.Product_Stock_Detail mProduct_Stock_Detail = new Product_Stock_Detail();
                            mProduct_Stock_Detail.StockID = Pro_StockID;
                            txtSerial = "txtSerial" + i.ToString();
                            txtCode = "txtCode" + i.ToString();
                            if (!( string.IsNullOrEmpty(Request.Form[txtCode]) && string.IsNullOrEmpty(Request.Form[txtSerial])))
                            {
                            mProduct_Stock_Detail.Code = Models.StockModel.Encrypt(Request.Form[txtCode].ToString());
                            mProduct_Stock_Detail.Serial = Request.Form[txtSerial].ToString();
                            mProduct_Stock_Detail.Status = stock.Status;
                            Pro_Stock_Detail = Models.StockModel.CreateProduct_Stock_Detail(mProduct_Stock_Detail);
                            }
                        }

                    }

                    //stockID = Models.StockModel.CreateStock(stock);

                    ViewData["Result"] = "Create Stock Success!";

                    return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/Stock/StockManage/" + sto.ProductID);
                }
                else
                {
                    return View("DetailStock", sto);
                }

            }
            catch
            {
                return View("DetailStock", new Models.Collection.StockCollection());
            }

        }

        public ActionResult EditStock(int id)
        {


            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();

            var sto = Models.StockModel.GetProductStockByID((int)id);
            var stock = new Models.Collection.StockCollection();

            stock.Quantity = sto.Quantity;
            stock.StockCode = sto.StockCode;
            stock.NotesStock = sto.NotesStock;
            stock.StockIn = sto.StockIn;
            stock.ModifyDate = sto.ModifyDate;
            stock.ProductID = sto.ProductID;
            if (sto.Status == 1)
            {
                stock.Status = true;
            }
            else if (sto.Status == 0)
            {
                stock.Status = false;
            }
            stock.StockID = sto.StockID;

            ViewData["IsAdd"] = false;

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
            {

                return View("DetailStock", stock);
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveEditStock(FormCollection collection)
        {
            var stock = new Models.Collection.StockCollection();
            TryUpdateModel(stock);
            int siteGuid = GetSiteGuid();

            try
            {

                //Update Stock
                SCSService.Product_Stock sto = Models.StockModel.GetProductStockByID((int)stock.StockID);

                sto.Quantity = stock.Quantity;

                sto.StockCode = stock.StockCode;
                sto.ModifyDate = DateTime.Now;
                sto.NotesStock = stock.NotesStock;
                sto.Status = stock.Status == true ? (byte)1 : (byte)0;
                sto.ProductID = stock.ProductID;

                //Update Product Stock
                Models.StockModel.UpdateProductStock(sto);

            }
            catch
            {
                return View("DetailStock", new Models.Collection.StockCollection());
            }
            return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/Stock/StockManage/" + stock.ProductID);
        }

        public ActionResult DeleteStock(int id, string returnUrl)
        {
            //Delete Product_Stock_Detail
            Models.StockModel.DeleteProduct_Stock_DetailById(id);//
            Models.StockModel.DeleteProductStock(id);
            ViewData["Result"] = "Delete success!";

            return Redirect(returnUrl);
        }

        public ActionResult ChangeStatusStock(int? id, int? proid)
        {
            Models.StockModel.UpdateStatusStock(id, proid);

            string outStr = "" + proid;
            return Json(outStr);
        }
        #endregion

        #region "Type Properties Manager"
        ///Phần này sẽ được chuyển sang trang quản lý (Master Management)
        ///
        public ActionResult AddTypeProperty()
        {
            var typeProperties = new Models.Collection.TypePropertiesCollection();
            int siteGuid = GetSiteGuid();
            
            int languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());

            ViewData["IsAdd"] = true;
            ViewData["ListLanguage"] = new SelectList(Models.StockModel.GetListLanguage(), "LanguagesID", "countryName", languageId);

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("DetailTypeProperties", typeProperties);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveAddTypeProperty(FormCollection collection)
        {
            var typeProperties = new Models.Collection.TypePropertiesCollection();
            TryUpdateModel(typeProperties);
            int typeId = 0;
            try
            {
                //Create Type Properties
                SCSService.Type_Property type = new Type_Property();
                type.TypePropertiesName = typeProperties.TypePropertiesName;
                type.TypePropertiesDes = typeProperties.TypePropertiesDes;
                type.TypePropertiesAbstract = typeProperties.TypePropertiesAbstract;
                if (typeProperties.Status != null)
                {
                    if (typeProperties.Status == true)
                        type.Status = 1;
                    else
                        type.Status = 0;
                }
                type.LanguagesID = typeProperties.LanguagesID;

                typeId = Models.StockModel.CreateTypeProperties(type);

                ViewData["Result"] = "Create Type Property Success!";

            }
            catch
            {
                return View("DetailTypeProperties", typeProperties);
            }
            return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/Stock/EditTypeProperty/" + typeId);
        }

        public ActionResult EditTypeProperty(int id)
        {
            ViewData["IsAdd"] = false;
            int siteGuid = GetSiteGuid();
            
            Type_Property type = Models.StockModel.GetTypeProperty(id);
            var typeProperty = new Models.Collection.TypePropertiesCollection();

            typeProperty.TypePropertiesName = type.TypePropertiesName;
            typeProperty.TypePropertiesDes = type.TypePropertiesDes;
            typeProperty.TypePropertiesAbstract = type.TypePropertiesAbstract;
            if (type.Status != null)
            {
                if (type.Status == 1)
                    typeProperty.Status = true;
                else if (type.Status == 0)
                    typeProperty.Status = false;
            }

            if (type.LanguagesID != null)
            {
                typeProperty.LanguagesID = (int)type.LanguagesID;
            }
           
            ViewData["ListLanguage"] = new SelectList(Models.StockModel.GetListLanguage(), "LanguagesID", "countryName", type.LanguagesID != null ? type.LanguagesID : 0);

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("DetailTypeProperties", typeProperty);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveEditTypeProperty(FormCollection collection)
        {
            var typeProperty = new Models.Collection.TypePropertiesCollection();
            TryUpdateModel(typeProperty);
            int siteGuid = GetSiteGuid();
            
            try
            {
                //Update Type Property
                SCSService.Type_Property type = Models.StockModel.GetTypeProperty((int)typeProperty.TypePropertiesID);
                type.TypePropertiesName = typeProperty.TypePropertiesName;
                type.TypePropertiesDes = typeProperty.TypePropertiesDes;
                type.TypePropertiesAbstract = typeProperty.TypePropertiesAbstract;
                type.TypePropertiesID = (int)typeProperty.TypePropertiesID;
                type.Status = typeProperty.Status == true ? (byte)1 : (byte)0;
                type.LanguagesID = typeProperty.LanguagesID;

                //Call Update method
                Models.StockModel.UpdateTypeProperty(type);

                ViewData["Result"] = "Update TypeProperty Success!";

            }
            catch
            {
                return View("DetailTypeProperties", typeProperty);
            }
            return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/Stock/EditTypeProperty/" + typeProperty.TypePropertiesID);
        }

        public static string GetGridThClass(ViewDataDictionary<SCS.Core.ViewModels.TypePropertyViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] != sortField)
                return "";

            if ((string)viewData["SortDirection"] == "Asc")
                return "asc";

            return "desc";
        }

        public static string GetGridThOnClick(ViewDataDictionary<SCS.Core.ViewModels.TypePropertyViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] == sortField && (string)viewData["SortDirection"] == "Asc")
                return "sort('" + sortField + "', 'Desc');";

            return "sort('" + sortField + "', 'Asc');";
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ListTypeProperty(int? id, string Name, int? StatusSearch)
        {
            int currentPage = 1;
            int pageSize = 2000;
            string sortField = "TypePropertiesID";
            string sortDirection = "Asc";

            int siteGuid = GetSiteGuid();
            

            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return ListTypeProperty(currentPage, pageSize, sortField, sortDirection, null, id, Name, StatusSearch, siteGuid);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult ListTypeProperty(int? currentPage, int? pageSize, string sortField, string sortDirection, string gridAction, int? id, string Name, int? StatusSearch, int? siteGuid)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            //id là mã product
            if (gridAction == "PageSizeChanged" || gridAction == "Sorted")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }


            if (pageSize == null)
            {
                pageSize = 2000;
            }

            if (siteGuid == null)
            {
                siteGuid = GetSiteGuid();
            }

            ViewData["currentPage"] = currentPage;

            var query = Models.StockModel.GetListTypeProperty(id, LanguageID, Name, StatusSearch).AsQueryable();
            int totalRows = query.Count();

            if (!String.IsNullOrEmpty(sortField))
            {
                var param = Expression.Parameter(typeof(Type_Property), "Type_Property");
                var sortExpression = Expression.Lambda<Func<Type_Property, object>>
                                        (Expression.Convert(Expression.Property(param, sortField), typeof(object)), param);

                if (sortDirection == "Asc")
                    query = query.OrderBy(sortExpression);
                else
                    query = query.OrderByDescending(sortExpression);
            }

            int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            if (totalPages != 1)
            {
                //paging
                query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
            }


            UpdateSorterViewData(sortField, sortDirection);
            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize);

            var result = query.ToList();

            if (totalRows == 0)
                result = new List<SCSService.Type_Property>();


            //// Set up our ViewModel
            var viewModel = new TypePropertyViewModels
            {
                ListTypeProperty = result,
                Name = Name,
                StatusSearch = StatusSearch
            };

            //// Return the view
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View(viewModel);
            //return View(result);
        }

        public ActionResult ChangeStatusTypeProperty(int? id, int? proid)
        {
            Models.StockModel.UpdateStatusTypeProperty(id, proid);

            string outStr = "" + proid;
            return Json(outStr);
        }

        public static bool CheckDeleteTypeProperty(int id)
        {
            int count = Models.StockModel.GetCountTypePropertyInProductTypeProperty(id);
            return count > 0 ? false : true;
        }

        public ActionResult DeleteTypeProperty(int id, string returnUrl)
        {
            if (CheckDeleteTypeProperty(id))
            {
                Models.StockModel.DeleteTypeProperty(id);
                ViewData["Result"] = "Delete success!";
            }
            else
                ViewData["Result"] = "Type Property have product. You can't delete";

            return Redirect(returnUrl);
        }

        public ActionResult DeleteProductTypeProperty(int id, string returnUrl)
        {
            Models.StockModel.DeleteProductTypeProperties(id);
            ViewData["Result"] = "Delete success!";
           
            return Redirect(returnUrl);
        }

        #endregion
        #region Ajax
        public ActionResult AjaxServer(int? id)
        {
            // lấy dữ liệu

            IList ListProStockDetail = StockModel.getListProductStockDetail(id);

            StringBuilder sb = new StringBuilder();

            sb.Append(@"<?xml version=""1.0"" ?>");
            sb.Append(@"<ProStockDetails>");
            //sb.Append(@"<ProStockDetail id='0'>Không tồn tại...</ProStockDetail>");

            foreach (Product_Stock_Detail proSD in ListProStockDetail)
            {
                sb.Append(@"<ProStockDetail id='" + proSD.ProductStockDetailID + "'><![CDATA['" + proSD.Serial + "']]><![CDATA['" + Models.StockModel.Decrypt(proSD.Code) + "']]></ProStockDetail>");
            }

            sb.Append(@"</ProStockDetails>");

            Response.Clear();
            Response.ContentType = "text/xml";
            Response.Write(sb.ToString());
            Response.End();
            return View();
        }

        public ActionResult AjaxEditCodeSerial(int id, string code, string serial)
        {
            StockModel.UpdateProduct_Stock_Detail(id, Models.StockModel.Encrypt(code), serial);
            return View();
        }
        #endregion
        #region save edit language Prouduct
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveAddProductLanguage(FormCollection collection)
        {
            int languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            var product = new Models.Collection.ProductCollection();
            TryUpdateModel(product);
            int proID = 0;
            int manaID = 0;
            int siteGuid = GetSiteGuid();
            try
            {
                if (product.ArrTypeProductID != "")
                {
                    //Create Product
                    SCSService.Product pro = new Product();
                    pro.ProductName = product.ProductName;
                    pro.ProductDes = product.ProductDes;
                    pro.Status = 1;
                    pro.Images = product.Images;
                    pro.Features = product.Features;
                    pro.CreateDate = DateTime.Now;
                    pro.CreateUser = int.Parse(Session["UserID"].ToString());
                    pro.Title = product.Title != string.Empty ? product.Title : pro.ProductName;
                    pro.MetaKeyword = product.MetaKeyword;
                    pro.MetaDescription = product.MetaDescription;
                    pro.ProductCode = product.ProductCode;

                    proID = Models.StockModel.CreateProduct(pro);

                    if (proID > 0)
                    {
                        var arr = product.ArrTypeProductID.ToString().Split(',');
                        foreach (var item in arr)
                        {
                            if (!string.IsNullOrEmpty(item))
                            {
                                //Add Product to Type_Product_Manage
                                SCSService.Type_Product_Manage manage = new Type_Product_Manage();
                                manage.ProductID = proID;
                                manage.TypeProductID = int.Parse(item);
                                manage.Status = 1;

                                manaID = Models.StockModel.CreateManageTypeProduct(manage);
                            }
                        }
                    }

                    //Update List ProductItem// Thay bằng tạo mới 
                    if (proID > 0)
                    {
                        ViewData["ListLanguage"] = new SelectList(Models.ModelsFontend.LanguageModel.GetListLanguageBySiteGuid(GetSiteGuid()), "LanguagesID", "countryName", languageId != null ? languageId : 0);
                        SelectList languages = (SelectList)ViewData["ListLanguage"];
                        foreach (SelectListItem language in languages)
                        {
                            if(language.Value!="1")
                            {
                                if (!string.IsNullOrEmpty(Request.Form["ProductName_Items" + language.Value]))
                                {
                                    SCSService.Product_Item item = new Product_Item();
                                    item.ProductName = Request.Form["ProductName_Items" + language.Value];
                                    item.ProductDes = Request.Form["ProductDes_Items"+ language.Value];
                                    item.Features = Request.Form["Features_Items" + language.Value];
                                    item.LanguagesID =int.Parse(language.Value);
                                    item.ProductID = proID;
                                    item.Title = Request.Form["Title_Items" + language.Value];
                                    item.MetaKeyword = Request.Form["MetaKeyword_Items" + language.Value];
                                    item.MetaDescription = Request.Form["MetaDescription_Items" + language.Value];

                                    Models.StockModel.CreateProductItem(item);
                                }
                            }
                        }
                    }
                    //Create 1 Item source
                    Product_Item it = new Product_Item();
                    it.ProductName = product.ProductName;
                    it.ProductDes = product.ProductDes;
                    it.Features = product.Features;
                    it.Title = product.Title != string.Empty ? product.Title : pro.ProductName;
                    it.MetaKeyword = product.MetaKeyword;
                    it.MetaDescription = product.MetaDescription;
                    it.LanguagesID = languageId;
                    it.ProductID = proID;
                    StockModel.CreateProductItem(it);


                    ViewData["Result"] = "Create Product Success!";

                    return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/Stock/ListProduct");
                }
                else
                {
                    ViewData["Result"] = "Please Choice Type Product!";
                    return View("DetailProduct", product);
                }

            }
            catch
            {
                return View("DetailProduct", new Models.Collection.ProductCollection());
            }
        }
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveEditProductLanguage(FormCollection collection)
        {
            var product = new Models.Collection.ProductCollection();
            TryUpdateModel(product);
            int siteGuid = GetSiteGuid();

            try
            {

                //Update Product
                SCSService.Product pro = Models.StockModel.GetProductByID(product.ProductID);
                pro.ProductName = product.ProductName;
                pro.ProductDes = product.ProductDes;
                pro.ProductCode = product.ProductCode;
                pro.Status = product.Active == true ? (byte)1 : (byte)0;
                pro.Images = product.Images;
                pro.Features = product.Features;
                pro.ModifyDate = DateTime.Now;
                pro.ModifyUser = int.Parse(Session["UserID"].ToString());
                pro.Title = product.Title;
                pro.MetaKeyword = product.MetaKeyword;
                pro.MetaDescription = product.MetaDescription;

                //Call Update method
                Models.StockModel.UpdateProduct(pro);

                //Update Ptoduct Manage
                //Check List . If type ptoduct in list Unchecked All ==> Not Update

                if (product.ArrTypeProductID != "")
                {
                    //Delete all Product in Type_Product_Manage
                    var list = Models.StockModel.GetListProductManageByProductID(pro.ProductID);
                    foreach (var item in list)
                    {
                        Models.StockModel.DeleteProductManage(item.ManageID);
                    }

                    //Create Product Type Manager New
                    int manaID = 0;

                    var arr = product.ArrTypeProductID.ToString().Split(',');
                    foreach (var item in arr)
                    {
                        if (!string.IsNullOrEmpty(item))
                        {
                            //Add Product to Type_Product_Manage
                            SCSService.Type_Product_Manage manage = new Type_Product_Manage();
                            manage.ProductID = pro.ProductID;
                            manage.TypeProductID = int.Parse(item);
                            manage.Status = 1;

                            manaID = Models.StockModel.CreateManageTypeProduct(manage);
                        }
                    }
                    int languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
                    ViewData["ListLanguage"] = new SelectList(Models.ModelsFontend.LanguageModel.GetListLanguageBySiteGuid(GetSiteGuid()), "LanguagesID", "countryName", languageId != null ? languageId : 0);
                    SelectList languages = (SelectList)ViewData["ListLanguage"];
                    foreach (SelectListItem language in languages)
                    {
                        if(language.Value!="1")
                        {
                        string productItemID = Request.Form["ProductItemId" + language.Value];
                        if (!string.IsNullOrEmpty(productItemID))
                        {
                        SCSService.Product_Item item = Models.StockModel.GetProductItemByID(int.Parse(productItemID));
                        item.ProductName = Request.Form["ProductName_Items" + language.Value];
                        item.ProductDes = Request.Form["ProductDes_Items" + language.Value];
                        item.Features = Request.Form["Features_Items" + language.Value];
                        item.LanguagesID = int.Parse(language.Value);
                        item.Title = Request.Form["Title_Items" + language.Value];
                        item.MetaKeyword = Request.Form["MetaKeyword_Items" + language.Value];
                        item.MetaDescription = Request.Form["MetaDescription_Items" + language.Value];

                        Models.StockModel.UpdateProductforItem(item);
                        }
                        }
                    
                    }

                    ViewData["Result"] = "Update Product Success!";
                    return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/Stock/ListProduct/");
                }
                else
                {
                    ViewData["Result"] = "Update Product failed!";
                    return View("DetailProduct", product);
                }
            }
            catch
            {
                return View("DetailProduct", new Models.Collection.ProductCollection());
            }
        }
        #endregion

    }
}